babylon.no-module.max.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. /** @hidden */
  414. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  415. // Rebuild shaders source code
  416. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  417. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  418. vertexCode = prefix + vertexCode;
  419. fragmentCode = prefix + fragmentCode;
  420. // Number lines of shaders source code
  421. var i = 2;
  422. var regex = /\n/gm;
  423. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  424. i = 2;
  425. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  426. // Dump shaders name and formatted source code
  427. if (this.name.vertexElement) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  430. }
  431. else if (this.name.vertex) {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  434. }
  435. else {
  436. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  437. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  438. }
  439. };
  440. ;
  441. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  442. var preparedSourceCode = this._processPrecision(sourceCode);
  443. if (this._engine.webGLVersion == 1) {
  444. callback(preparedSourceCode);
  445. return;
  446. }
  447. // Already converted
  448. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  449. callback(preparedSourceCode.replace("#version 300 es", ""));
  450. return;
  451. }
  452. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  453. // Remove extensions
  454. // #extension GL_OES_standard_derivatives : enable
  455. // #extension GL_EXT_shader_texture_lod : enable
  456. // #extension GL_EXT_frag_depth : enable
  457. // #extension GL_EXT_draw_buffers : require
  458. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  459. var result = preparedSourceCode.replace(regex, "");
  460. // Migrate to GLSL v300
  461. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  462. result = result.replace(/attribute[ \t]/g, "in ");
  463. result = result.replace(/[ \t]attribute/g, " in");
  464. if (isFragment) {
  465. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  467. result = result.replace(/texture2D\s*\(/g, "texture(");
  468. result = result.replace(/textureCube\s*\(/g, "texture(");
  469. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  470. result = result.replace(/gl_FragColor/g, "glFragColor");
  471. result = result.replace(/gl_FragData/g, "glFragData");
  472. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  473. }
  474. callback(result);
  475. };
  476. Effect.prototype._processIncludes = function (sourceCode, callback) {
  477. var _this = this;
  478. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  479. var match = regex.exec(sourceCode);
  480. var returnValue = new String(sourceCode);
  481. while (match != null) {
  482. var includeFile = match[1];
  483. // Uniform declaration
  484. if (includeFile.indexOf("__decl__") !== -1) {
  485. includeFile = includeFile.replace(/__decl__/, "");
  486. if (this._engine.supportsUniformBuffers) {
  487. includeFile = includeFile.replace(/Vertex/, "Ubo");
  488. includeFile = includeFile.replace(/Fragment/, "Ubo");
  489. }
  490. includeFile = includeFile + "Declaration";
  491. }
  492. if (Effect.IncludesShadersStore[includeFile]) {
  493. // Substitution
  494. var includeContent = Effect.IncludesShadersStore[includeFile];
  495. if (match[2]) {
  496. var splits = match[3].split(",");
  497. for (var index = 0; index < splits.length; index += 2) {
  498. var source = new RegExp(splits[index], "g");
  499. var dest = splits[index + 1];
  500. includeContent = includeContent.replace(source, dest);
  501. }
  502. }
  503. if (match[4]) {
  504. var indexString = match[5];
  505. if (indexString.indexOf("..") !== -1) {
  506. var indexSplits = indexString.split("..");
  507. var minIndex = parseInt(indexSplits[0]);
  508. var maxIndex = parseInt(indexSplits[1]);
  509. var sourceIncludeContent = includeContent.slice(0);
  510. includeContent = "";
  511. if (isNaN(maxIndex)) {
  512. maxIndex = this._indexParameters[indexSplits[1]];
  513. }
  514. for (var i = minIndex; i < maxIndex; i++) {
  515. if (!this._engine.supportsUniformBuffers) {
  516. // Ubo replacement
  517. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  518. return p1 + "{X}";
  519. });
  520. }
  521. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  522. }
  523. }
  524. else {
  525. if (!this._engine.supportsUniformBuffers) {
  526. // Ubo replacement
  527. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  528. return p1 + "{X}";
  529. });
  530. }
  531. includeContent = includeContent.replace(/\{X\}/g, indexString);
  532. }
  533. }
  534. // Replace
  535. returnValue = returnValue.replace(match[0], includeContent);
  536. }
  537. else {
  538. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  539. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  540. Effect.IncludesShadersStore[includeFile] = fileContent;
  541. _this._processIncludes(returnValue, callback);
  542. });
  543. return;
  544. }
  545. match = regex.exec(sourceCode);
  546. }
  547. callback(returnValue);
  548. };
  549. Effect.prototype._processPrecision = function (source) {
  550. if (source.indexOf("precision highp float") === -1) {
  551. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  552. source = "precision mediump float;\n" + source;
  553. }
  554. else {
  555. source = "precision highp float;\n" + source;
  556. }
  557. }
  558. else {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  560. source = source.replace("precision highp float", "precision mediump float");
  561. }
  562. }
  563. return source;
  564. };
  565. /**
  566. * Recompiles the webGL program
  567. * @param vertexSourceCode The source code for the vertex shader.
  568. * @param fragmentSourceCode The source code for the fragment shader.
  569. * @param onCompiled Callback called when completed.
  570. * @param onError Callback called on error.
  571. */
  572. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  573. var _this = this;
  574. this._isReady = false;
  575. this._vertexSourceCodeOverride = vertexSourceCode;
  576. this._fragmentSourceCodeOverride = fragmentSourceCode;
  577. this.onError = function (effect, error) {
  578. if (onError) {
  579. onError(error);
  580. }
  581. };
  582. this.onCompiled = function () {
  583. var scenes = _this.getEngine().scenes;
  584. for (var i = 0; i < scenes.length; i++) {
  585. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  586. }
  587. if (onCompiled) {
  588. onCompiled(_this._program);
  589. }
  590. };
  591. this._fallbacks = null;
  592. this._prepareEffect();
  593. };
  594. /**
  595. * Gets the uniform locations of the the specified variable names
  596. * @param names THe names of the variables to lookup.
  597. * @returns Array of locations in the same order as variable names.
  598. */
  599. Effect.prototype.getSpecificUniformLocations = function (names) {
  600. var engine = this._engine;
  601. return engine.getUniforms(this._program, names);
  602. };
  603. /**
  604. * Prepares the effect
  605. */
  606. Effect.prototype._prepareEffect = function () {
  607. var attributesNames = this._attributesNames;
  608. var defines = this.defines;
  609. var fallbacks = this._fallbacks;
  610. this._valueCache = {};
  611. var previousProgram = this._program;
  612. try {
  613. var engine = this._engine;
  614. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  615. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  616. }
  617. else {
  618. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  619. }
  620. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  621. if (engine.supportsUniformBuffers) {
  622. for (var name in this._uniformBuffersNames) {
  623. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  624. }
  625. }
  626. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  627. this._attributes = engine.getAttributes(this._program, attributesNames);
  628. var index;
  629. for (index = 0; index < this._samplers.length; index++) {
  630. var sampler = this.getUniform(this._samplers[index]);
  631. if (sampler == null) {
  632. this._samplers.splice(index, 1);
  633. index--;
  634. }
  635. }
  636. engine.bindSamplers(this);
  637. this._compilationError = "";
  638. this._isReady = true;
  639. if (this.onCompiled) {
  640. this.onCompiled(this);
  641. }
  642. this.onCompileObservable.notifyObservers(this);
  643. this.onCompileObservable.clear();
  644. // Unbind mesh reference in fallbacks
  645. if (this._fallbacks) {
  646. this._fallbacks.unBindMesh();
  647. }
  648. if (previousProgram) {
  649. this.getEngine()._deleteProgram(previousProgram);
  650. }
  651. }
  652. catch (e) {
  653. this._compilationError = e.message;
  654. // Let's go through fallbacks then
  655. BABYLON.Tools.Error("Unable to compile effect:");
  656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  657. return " " + uniform;
  658. }));
  659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  660. return " " + attribute;
  661. }));
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * 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)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * 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
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function (request) {
  9097. if (request && request.status > 400) {
  9098. if (onError) {
  9099. onError(request);
  9100. }
  9101. }
  9102. else {
  9103. if (!aborted) {
  9104. requestFile();
  9105. }
  9106. }
  9107. };
  9108. var loadFromIndexedDB = function () {
  9109. // TODO: database needs to support aborting and should return a IFileRequest
  9110. if (aborted) {
  9111. return;
  9112. }
  9113. if (database) {
  9114. database.loadFileFromDB(url, function (data) {
  9115. if (!aborted) {
  9116. onSuccess(data);
  9117. }
  9118. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9119. }, onProgress ? function (event) {
  9120. if (!aborted) {
  9121. onProgress(event);
  9122. }
  9123. } : undefined, noIndexedDB_1, useArrayBuffer);
  9124. }
  9125. };
  9126. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9127. }
  9128. else {
  9129. requestFile();
  9130. }
  9131. return fileRequest;
  9132. };
  9133. /**
  9134. * Load a script (identified by an url). When the url returns, the
  9135. * content of this file is added into a new script element, attached to the DOM (body element)
  9136. */
  9137. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9138. var head = document.getElementsByTagName('head')[0];
  9139. var script = document.createElement('script');
  9140. script.type = 'text/javascript';
  9141. script.src = scriptUrl;
  9142. script.onload = function () {
  9143. if (onSuccess) {
  9144. onSuccess();
  9145. }
  9146. };
  9147. script.onerror = function (e) {
  9148. if (onError) {
  9149. onError("Unable to load script '" + scriptUrl + "'", e);
  9150. }
  9151. };
  9152. head.appendChild(script);
  9153. };
  9154. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9155. var reader = new FileReader();
  9156. var request = {
  9157. onCompleteObservable: new BABYLON.Observable(),
  9158. abort: function () { return reader.abort(); },
  9159. };
  9160. reader.onloadend = function (e) {
  9161. request.onCompleteObservable.notifyObservers(request);
  9162. };
  9163. reader.onload = function (e) {
  9164. //target doesn't have result from ts 1.3
  9165. callback(e.target['result']);
  9166. };
  9167. reader.onprogress = progressCallback;
  9168. reader.readAsDataURL(fileToLoad);
  9169. return request;
  9170. };
  9171. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9172. var reader = new FileReader();
  9173. var request = {
  9174. onCompleteObservable: new BABYLON.Observable(),
  9175. abort: function () { return reader.abort(); },
  9176. };
  9177. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9178. reader.onerror = function (e) {
  9179. Tools.Log("Error while reading file: " + fileToLoad.name);
  9180. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9181. };
  9182. reader.onload = function (e) {
  9183. //target doesn't have result from ts 1.3
  9184. callback(e.target['result']);
  9185. };
  9186. if (progressCallBack) {
  9187. reader.onprogress = progressCallBack;
  9188. }
  9189. if (!useArrayBuffer) {
  9190. // Asynchronous read
  9191. reader.readAsText(fileToLoad);
  9192. }
  9193. else {
  9194. reader.readAsArrayBuffer(fileToLoad);
  9195. }
  9196. return request;
  9197. };
  9198. //returns a downloadable url to a file content.
  9199. Tools.FileAsURL = function (content) {
  9200. var fileBlob = new Blob([content]);
  9201. var url = window.URL || window.webkitURL;
  9202. var link = url.createObjectURL(fileBlob);
  9203. return link;
  9204. };
  9205. // Misc.
  9206. Tools.Format = function (value, decimals) {
  9207. if (decimals === void 0) { decimals = 2; }
  9208. return value.toFixed(decimals);
  9209. };
  9210. Tools.CheckExtends = function (v, min, max) {
  9211. if (v.x < min.x)
  9212. min.x = v.x;
  9213. if (v.y < min.y)
  9214. min.y = v.y;
  9215. if (v.z < min.z)
  9216. min.z = v.z;
  9217. if (v.x > max.x)
  9218. max.x = v.x;
  9219. if (v.y > max.y)
  9220. max.y = v.y;
  9221. if (v.z > max.z)
  9222. max.z = v.z;
  9223. };
  9224. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9225. for (var prop in source) {
  9226. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9227. continue;
  9228. }
  9229. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9230. continue;
  9231. }
  9232. var sourceValue = source[prop];
  9233. var typeOfSourceValue = typeof sourceValue;
  9234. if (typeOfSourceValue === "function") {
  9235. continue;
  9236. }
  9237. try {
  9238. if (typeOfSourceValue === "object") {
  9239. if (sourceValue instanceof Array) {
  9240. destination[prop] = [];
  9241. if (sourceValue.length > 0) {
  9242. if (typeof sourceValue[0] == "object") {
  9243. for (var index = 0; index < sourceValue.length; index++) {
  9244. var clonedValue = cloneValue(sourceValue[index], destination);
  9245. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9246. destination[prop].push(clonedValue);
  9247. }
  9248. }
  9249. }
  9250. else {
  9251. destination[prop] = sourceValue.slice(0);
  9252. }
  9253. }
  9254. }
  9255. else {
  9256. destination[prop] = cloneValue(sourceValue, destination);
  9257. }
  9258. }
  9259. else {
  9260. destination[prop] = sourceValue;
  9261. }
  9262. }
  9263. catch (e) {
  9264. // Just ignore error (it could be because of a read-only property)
  9265. }
  9266. }
  9267. };
  9268. Tools.IsEmpty = function (obj) {
  9269. for (var i in obj) {
  9270. if (obj.hasOwnProperty(i)) {
  9271. return false;
  9272. }
  9273. }
  9274. return true;
  9275. };
  9276. Tools.RegisterTopRootEvents = function (events) {
  9277. for (var index = 0; index < events.length; index++) {
  9278. var event = events[index];
  9279. window.addEventListener(event.name, event.handler, false);
  9280. try {
  9281. if (window.parent) {
  9282. window.parent.addEventListener(event.name, event.handler, false);
  9283. }
  9284. }
  9285. catch (e) {
  9286. // Silently fails...
  9287. }
  9288. }
  9289. };
  9290. Tools.UnregisterTopRootEvents = function (events) {
  9291. for (var index = 0; index < events.length; index++) {
  9292. var event = events[index];
  9293. window.removeEventListener(event.name, event.handler);
  9294. try {
  9295. if (window.parent) {
  9296. window.parent.removeEventListener(event.name, event.handler);
  9297. }
  9298. }
  9299. catch (e) {
  9300. // Silently fails...
  9301. }
  9302. }
  9303. };
  9304. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9305. if (mimeType === void 0) { mimeType = "image/png"; }
  9306. // Read the contents of the framebuffer
  9307. var numberOfChannelsByLine = width * 4;
  9308. var halfHeight = height / 2;
  9309. //Reading datas from WebGL
  9310. var data = engine.readPixels(0, 0, width, height);
  9311. //To flip image on Y axis.
  9312. for (var i = 0; i < halfHeight; i++) {
  9313. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9314. var currentCell = j + i * numberOfChannelsByLine;
  9315. var targetLine = height - i - 1;
  9316. var targetCell = j + targetLine * numberOfChannelsByLine;
  9317. var temp = data[currentCell];
  9318. data[currentCell] = data[targetCell];
  9319. data[targetCell] = temp;
  9320. }
  9321. }
  9322. // Create a 2D canvas to store the result
  9323. if (!screenshotCanvas) {
  9324. screenshotCanvas = document.createElement('canvas');
  9325. }
  9326. screenshotCanvas.width = width;
  9327. screenshotCanvas.height = height;
  9328. var context = screenshotCanvas.getContext('2d');
  9329. if (context) {
  9330. // Copy the pixels to a 2D canvas
  9331. var imageData = context.createImageData(width, height);
  9332. var castData = (imageData.data);
  9333. castData.set(data);
  9334. context.putImageData(imageData, 0, 0);
  9335. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9336. }
  9337. };
  9338. /**
  9339. * Converts the canvas data to blob.
  9340. * This acts as a polyfill for browsers not supporting the to blob function.
  9341. * @param canvas Defines the canvas to extract the data from
  9342. * @param successCallback Defines the callback triggered once the data are available
  9343. * @param mimeType Defines the mime type of the result
  9344. */
  9345. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9346. if (mimeType === void 0) { mimeType = "image/png"; }
  9347. // We need HTMLCanvasElement.toBlob for HD screenshots
  9348. if (!canvas.toBlob) {
  9349. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9350. canvas.toBlob = function (callback, type, quality) {
  9351. var _this = this;
  9352. setTimeout(function () {
  9353. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9354. for (var i = 0; i < len; i++) {
  9355. arr[i] = binStr.charCodeAt(i);
  9356. }
  9357. callback(new Blob([arr]));
  9358. });
  9359. };
  9360. }
  9361. canvas.toBlob(function (blob) {
  9362. successCallback(blob);
  9363. }, mimeType);
  9364. };
  9365. /**
  9366. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9367. * @param successCallback Defines the callback triggered once the data are available
  9368. * @param mimeType Defines the mime type of the result
  9369. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9370. */
  9371. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9372. if (mimeType === void 0) { mimeType = "image/png"; }
  9373. if (successCallback) {
  9374. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9375. successCallback(base64Image);
  9376. }
  9377. else {
  9378. this.ToBlob(screenshotCanvas, function (blob) {
  9379. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9380. if (("download" in document.createElement("a"))) {
  9381. if (!fileName) {
  9382. var date = new Date();
  9383. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9384. fileName = "screenshot_" + stringDate + ".png";
  9385. }
  9386. Tools.Download(blob, fileName);
  9387. }
  9388. else {
  9389. var url = URL.createObjectURL(blob);
  9390. var newWindow = window.open("");
  9391. if (!newWindow)
  9392. return;
  9393. var img = newWindow.document.createElement("img");
  9394. img.onload = function () {
  9395. // no longer need to read the blob so it's revoked
  9396. URL.revokeObjectURL(url);
  9397. };
  9398. img.src = url;
  9399. newWindow.document.body.appendChild(img);
  9400. }
  9401. }, mimeType);
  9402. }
  9403. };
  9404. /**
  9405. * Downloads a blob in the browser
  9406. * @param blob defines the blob to download
  9407. * @param fileName defines the name of the downloaded file
  9408. */
  9409. Tools.Download = function (blob, fileName) {
  9410. var url = window.URL.createObjectURL(blob);
  9411. var a = document.createElement("a");
  9412. document.body.appendChild(a);
  9413. a.style.display = "none";
  9414. a.href = url;
  9415. a.download = fileName;
  9416. a.addEventListener("click", function () {
  9417. if (a.parentElement) {
  9418. a.parentElement.removeChild(a);
  9419. }
  9420. });
  9421. a.click();
  9422. window.URL.revokeObjectURL(url);
  9423. };
  9424. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9425. if (mimeType === void 0) { mimeType = "image/png"; }
  9426. var width;
  9427. var height;
  9428. // If a precision value is specified
  9429. if (size.precision) {
  9430. width = Math.round(engine.getRenderWidth() * size.precision);
  9431. height = Math.round(width / engine.getAspectRatio(camera));
  9432. }
  9433. else if (size.width && size.height) {
  9434. width = size.width;
  9435. height = size.height;
  9436. }
  9437. //If passing only width, computing height to keep display canvas ratio.
  9438. else if (size.width && !size.height) {
  9439. width = size.width;
  9440. height = Math.round(width / engine.getAspectRatio(camera));
  9441. }
  9442. //If passing only height, computing width to keep display canvas ratio.
  9443. else if (size.height && !size.width) {
  9444. height = size.height;
  9445. width = Math.round(height * engine.getAspectRatio(camera));
  9446. }
  9447. //Assuming here that "size" parameter is a number
  9448. else if (!isNaN(size)) {
  9449. height = size;
  9450. width = size;
  9451. }
  9452. else {
  9453. Tools.Error("Invalid 'size' parameter !");
  9454. return;
  9455. }
  9456. if (!screenshotCanvas) {
  9457. screenshotCanvas = document.createElement('canvas');
  9458. }
  9459. screenshotCanvas.width = width;
  9460. screenshotCanvas.height = height;
  9461. var renderContext = screenshotCanvas.getContext("2d");
  9462. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9463. var newWidth = width;
  9464. var newHeight = newWidth / ratio;
  9465. if (newHeight > height) {
  9466. newHeight = height;
  9467. newWidth = newHeight * ratio;
  9468. }
  9469. var offsetX = Math.max(0, width - newWidth) / 2;
  9470. var offsetY = Math.max(0, height - newHeight) / 2;
  9471. var renderingCanvas = engine.getRenderingCanvas();
  9472. if (renderContext && renderingCanvas) {
  9473. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9474. }
  9475. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9476. };
  9477. /**
  9478. * Generates an image screenshot from the specified camera.
  9479. *
  9480. * @param engine The engine to use for rendering
  9481. * @param camera The camera to use for rendering
  9482. * @param size This parameter can be set to a single number or to an object with the
  9483. * following (optional) properties: precision, width, height. If a single number is passed,
  9484. * it will be used for both width and height. If an object is passed, the screenshot size
  9485. * will be derived from the parameters. The precision property is a multiplier allowing
  9486. * rendering at a higher or lower resolution.
  9487. * @param successCallback The callback receives a single parameter which contains the
  9488. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9489. * src parameter of an <img> to display it.
  9490. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9491. * Check your browser for supported MIME types.
  9492. * @param samples Texture samples (default: 1)
  9493. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9494. * @param fileName A name for for the downloaded file.
  9495. * @constructor
  9496. */
  9497. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9498. if (mimeType === void 0) { mimeType = "image/png"; }
  9499. if (samples === void 0) { samples = 1; }
  9500. if (antialiasing === void 0) { antialiasing = false; }
  9501. var width;
  9502. var height;
  9503. //If a precision value is specified
  9504. if (size.precision) {
  9505. width = Math.round(engine.getRenderWidth() * size.precision);
  9506. height = Math.round(width / engine.getAspectRatio(camera));
  9507. size = { width: width, height: height };
  9508. }
  9509. else if (size.width && size.height) {
  9510. width = size.width;
  9511. height = size.height;
  9512. }
  9513. //If passing only width, computing height to keep display canvas ratio.
  9514. else if (size.width && !size.height) {
  9515. width = size.width;
  9516. height = Math.round(width / engine.getAspectRatio(camera));
  9517. size = { width: width, height: height };
  9518. }
  9519. //If passing only height, computing width to keep display canvas ratio.
  9520. else if (size.height && !size.width) {
  9521. height = size.height;
  9522. width = Math.round(height * engine.getAspectRatio(camera));
  9523. size = { width: width, height: height };
  9524. }
  9525. //Assuming here that "size" parameter is a number
  9526. else if (!isNaN(size)) {
  9527. height = size;
  9528. width = size;
  9529. }
  9530. else {
  9531. Tools.Error("Invalid 'size' parameter !");
  9532. return;
  9533. }
  9534. var scene = camera.getScene();
  9535. var previousCamera = null;
  9536. if (scene.activeCamera !== camera) {
  9537. previousCamera = scene.activeCamera;
  9538. scene.activeCamera = camera;
  9539. }
  9540. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9541. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9542. texture.renderList = null;
  9543. texture.samples = samples;
  9544. if (antialiasing) {
  9545. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9546. }
  9547. texture.onAfterRenderObservable.add(function () {
  9548. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9549. });
  9550. scene.incrementRenderId();
  9551. scene.resetCachedMaterial();
  9552. texture.render(true);
  9553. texture.dispose();
  9554. if (previousCamera) {
  9555. scene.activeCamera = previousCamera;
  9556. }
  9557. camera.getProjectionMatrix(true); // Force cache refresh;
  9558. };
  9559. // XHR response validator for local file scenario
  9560. Tools.ValidateXHRData = function (xhr, dataType) {
  9561. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9562. if (dataType === void 0) { dataType = 7; }
  9563. try {
  9564. if (dataType & 1) {
  9565. if (xhr.responseText && xhr.responseText.length > 0) {
  9566. return true;
  9567. }
  9568. else if (dataType === 1) {
  9569. return false;
  9570. }
  9571. }
  9572. if (dataType & 2) {
  9573. // Check header width and height since there is no "TGA" magic number
  9574. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9575. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9576. return true;
  9577. }
  9578. else if (dataType === 2) {
  9579. return false;
  9580. }
  9581. }
  9582. if (dataType & 4) {
  9583. // Check for the "DDS" magic number
  9584. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9585. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9586. return true;
  9587. }
  9588. else {
  9589. return false;
  9590. }
  9591. }
  9592. }
  9593. catch (e) {
  9594. // Global protection
  9595. }
  9596. return false;
  9597. };
  9598. /**
  9599. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9600. * Be aware Math.random() could cause collisions, but:
  9601. * "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"
  9602. */
  9603. Tools.RandomId = function () {
  9604. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9605. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9606. return v.toString(16);
  9607. });
  9608. };
  9609. /**
  9610. * Test if the given uri is a base64 string.
  9611. * @param uri The uri to test
  9612. * @return True if the uri is a base64 string or false otherwise.
  9613. */
  9614. Tools.IsBase64 = function (uri) {
  9615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9616. };
  9617. /**
  9618. * Decode the given base64 uri.
  9619. * @param uri The uri to decode
  9620. * @return The decoded base64 data.
  9621. */
  9622. Tools.DecodeBase64 = function (uri) {
  9623. var decodedString = atob(uri.split(",")[1]);
  9624. var bufferLength = decodedString.length;
  9625. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9626. for (var i = 0; i < bufferLength; i++) {
  9627. bufferView[i] = decodedString.charCodeAt(i);
  9628. }
  9629. return bufferView.buffer;
  9630. };
  9631. Object.defineProperty(Tools, "NoneLogLevel", {
  9632. get: function () {
  9633. return Tools._NoneLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "MessageLogLevel", {
  9639. get: function () {
  9640. return Tools._MessageLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "WarningLogLevel", {
  9646. get: function () {
  9647. return Tools._WarningLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "ErrorLogLevel", {
  9653. get: function () {
  9654. return Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "AllLogLevel", {
  9660. get: function () {
  9661. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Tools._AddLogEntry = function (entry) {
  9667. Tools._LogCache = entry + Tools._LogCache;
  9668. if (Tools.OnNewCacheEntry) {
  9669. Tools.OnNewCacheEntry(entry);
  9670. }
  9671. };
  9672. Tools._FormatMessage = function (message) {
  9673. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9674. var date = new Date();
  9675. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9676. };
  9677. Tools._LogDisabled = function (message) {
  9678. // nothing to do
  9679. };
  9680. Tools._LogEnabled = function (message) {
  9681. var formattedMessage = Tools._FormatMessage(message);
  9682. console.log("BJS - " + formattedMessage);
  9683. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9684. Tools._AddLogEntry(entry);
  9685. };
  9686. Tools._WarnDisabled = function (message) {
  9687. // nothing to do
  9688. };
  9689. Tools._WarnEnabled = function (message) {
  9690. var formattedMessage = Tools._FormatMessage(message);
  9691. console.warn("BJS - " + formattedMessage);
  9692. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9693. Tools._AddLogEntry(entry);
  9694. };
  9695. Tools._ErrorDisabled = function (message) {
  9696. // nothing to do
  9697. };
  9698. Tools._ErrorEnabled = function (message) {
  9699. Tools.errorsCount++;
  9700. var formattedMessage = Tools._FormatMessage(message);
  9701. console.error("BJS - " + formattedMessage);
  9702. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9703. Tools._AddLogEntry(entry);
  9704. };
  9705. Object.defineProperty(Tools, "LogCache", {
  9706. get: function () {
  9707. return Tools._LogCache;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Tools.ClearLogCache = function () {
  9713. Tools._LogCache = "";
  9714. Tools.errorsCount = 0;
  9715. };
  9716. Object.defineProperty(Tools, "LogLevels", {
  9717. set: function (level) {
  9718. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9719. Tools.Log = Tools._LogEnabled;
  9720. }
  9721. else {
  9722. Tools.Log = Tools._LogDisabled;
  9723. }
  9724. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9725. Tools.Warn = Tools._WarnEnabled;
  9726. }
  9727. else {
  9728. Tools.Warn = Tools._WarnDisabled;
  9729. }
  9730. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9731. Tools.Error = Tools._ErrorEnabled;
  9732. }
  9733. else {
  9734. Tools.Error = Tools._ErrorDisabled;
  9735. }
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Tools.IsWindowObjectExist = function () {
  9741. return (typeof window) !== "undefined";
  9742. };
  9743. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceNoneLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceUserMarkLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9758. get: function () {
  9759. return Tools._PerformanceConsoleLogLevel;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9765. set: function (level) {
  9766. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9767. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9768. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9769. return;
  9770. }
  9771. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9772. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9773. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9774. return;
  9775. }
  9776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9777. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9783. };
  9784. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9785. };
  9786. Tools._StartUserMark = function (counterName, condition) {
  9787. if (condition === void 0) { condition = true; }
  9788. if (!Tools._performance) {
  9789. if (!Tools.IsWindowObjectExist()) {
  9790. return;
  9791. }
  9792. Tools._performance = window.performance;
  9793. }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-Begin");
  9798. };
  9799. Tools._EndUserMark = function (counterName, condition) {
  9800. if (condition === void 0) { condition = true; }
  9801. if (!condition || !Tools._performance.mark) {
  9802. return;
  9803. }
  9804. Tools._performance.mark(counterName + "-End");
  9805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9806. };
  9807. Tools._StartPerformanceConsole = function (counterName, condition) {
  9808. if (condition === void 0) { condition = true; }
  9809. if (!condition) {
  9810. return;
  9811. }
  9812. Tools._StartUserMark(counterName, condition);
  9813. if (console.time) {
  9814. console.time(counterName);
  9815. }
  9816. };
  9817. Tools._EndPerformanceConsole = function (counterName, condition) {
  9818. if (condition === void 0) { condition = true; }
  9819. if (!condition) {
  9820. return;
  9821. }
  9822. Tools._EndUserMark(counterName, condition);
  9823. if (console.time) {
  9824. console.timeEnd(counterName);
  9825. }
  9826. };
  9827. Object.defineProperty(Tools, "Now", {
  9828. get: function () {
  9829. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9830. return window.performance.now();
  9831. }
  9832. return Date.now();
  9833. },
  9834. enumerable: true,
  9835. configurable: true
  9836. });
  9837. /**
  9838. * This method will return the name of the class used to create the instance of the given object.
  9839. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9840. * @param object the object to get the class name from
  9841. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9842. */
  9843. Tools.GetClassName = function (object, isType) {
  9844. if (isType === void 0) { isType = false; }
  9845. var name = null;
  9846. if (!isType && object.getClassName) {
  9847. name = object.getClassName();
  9848. }
  9849. else {
  9850. if (object instanceof Object) {
  9851. var classObj = isType ? object : Object.getPrototypeOf(object);
  9852. name = classObj.constructor["__bjsclassName__"];
  9853. }
  9854. if (!name) {
  9855. name = typeof object;
  9856. }
  9857. }
  9858. return name;
  9859. };
  9860. Tools.First = function (array, predicate) {
  9861. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9862. var el = array_1[_i];
  9863. if (predicate(el)) {
  9864. return el;
  9865. }
  9866. }
  9867. return null;
  9868. };
  9869. /**
  9870. * This method will return the name of the full name of the class, including its owning module (if any).
  9871. * 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).
  9872. * @param object the object to get the class name from
  9873. * @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.
  9874. */
  9875. Tools.getFullClassName = function (object, isType) {
  9876. if (isType === void 0) { isType = false; }
  9877. var className = null;
  9878. var moduleName = null;
  9879. if (!isType && object.getClassName) {
  9880. className = object.getClassName();
  9881. }
  9882. else {
  9883. if (object instanceof Object) {
  9884. var classObj = isType ? object : Object.getPrototypeOf(object);
  9885. className = classObj.constructor["__bjsclassName__"];
  9886. moduleName = classObj.constructor["__bjsmoduleName__"];
  9887. }
  9888. if (!className) {
  9889. className = typeof object;
  9890. }
  9891. }
  9892. if (!className) {
  9893. return null;
  9894. }
  9895. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9896. };
  9897. /**
  9898. * 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.
  9899. * @param array
  9900. */
  9901. Tools.arrayOrStringFeeder = function (array) {
  9902. return function (index) {
  9903. if (index >= array.length) {
  9904. return null;
  9905. }
  9906. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9907. if (val && val.getHashCode) {
  9908. val = val.getHashCode();
  9909. }
  9910. if (typeof val === "string") {
  9911. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9912. }
  9913. return val;
  9914. };
  9915. };
  9916. /**
  9917. * Compute the hashCode of a stream of number
  9918. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9919. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9920. * @return the hash code computed
  9921. */
  9922. Tools.hashCodeFromStream = function (feeder) {
  9923. // Based from here: http://stackoverflow.com/a/7616484/802124
  9924. var hash = 0;
  9925. var index = 0;
  9926. var chr = feeder(index++);
  9927. while (chr != null) {
  9928. hash = ((hash << 5) - hash) + chr;
  9929. hash |= 0; // Convert to 32bit integer
  9930. chr = feeder(index++);
  9931. }
  9932. return hash;
  9933. };
  9934. /**
  9935. * Returns a promise that resolves after the given amount of time.
  9936. * @param delay Number of milliseconds to delay
  9937. * @returns Promise that resolves after the given amount of time
  9938. */
  9939. Tools.DelayAsync = function (delay) {
  9940. return new Promise(function (resolve) {
  9941. setTimeout(function () {
  9942. resolve();
  9943. }, delay);
  9944. });
  9945. };
  9946. /**
  9947. * Gets the current gradient from an array of IValueGradient
  9948. * @param ratio defines the current ratio to get
  9949. * @param gradients defines the array of IValueGradient
  9950. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9951. */
  9952. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9953. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9954. var currentGradient = gradients[gradientIndex];
  9955. var nextGradient = gradients[gradientIndex + 1];
  9956. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9957. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9958. updateFunc(currentGradient, nextGradient, scale);
  9959. }
  9960. }
  9961. };
  9962. Tools.BaseUrl = "";
  9963. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9964. /**
  9965. * Default behaviour for cors in the application.
  9966. * It can be a string if the expected behavior is identical in the entire app.
  9967. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9968. */
  9969. Tools.CorsBehavior = "anonymous";
  9970. Tools.UseFallbackTexture = true;
  9971. /**
  9972. * Use this object to register external classes like custom textures or material
  9973. * to allow the laoders to instantiate them
  9974. */
  9975. Tools.RegisteredExternalClasses = {};
  9976. // Used in case of a texture loading problem
  9977. 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";
  9978. Tools._tmpFloatArray = new Float32Array(1);
  9979. Tools.PreprocessUrl = function (url) {
  9980. return url;
  9981. };
  9982. // Logs
  9983. Tools._NoneLogLevel = 0;
  9984. Tools._MessageLogLevel = 1;
  9985. Tools._WarningLogLevel = 2;
  9986. Tools._ErrorLogLevel = 4;
  9987. Tools._LogCache = "";
  9988. Tools.errorsCount = 0;
  9989. Tools.Log = Tools._LogEnabled;
  9990. Tools.Warn = Tools._WarnEnabled;
  9991. Tools.Error = Tools._ErrorEnabled;
  9992. // Performances
  9993. Tools._PerformanceNoneLogLevel = 0;
  9994. Tools._PerformanceUserMarkLogLevel = 1;
  9995. Tools._PerformanceConsoleLogLevel = 2;
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9998. return Tools;
  9999. }());
  10000. BABYLON.Tools = Tools;
  10001. /**
  10002. * This class is used to track a performance counter which is number based.
  10003. * The user has access to many properties which give statistics of different nature
  10004. *
  10005. * The implementer can track two kinds of Performance Counter: time and count
  10006. * 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.
  10007. * 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.
  10008. */
  10009. var PerfCounter = /** @class */ (function () {
  10010. function PerfCounter() {
  10011. this._startMonitoringTime = 0;
  10012. this._min = 0;
  10013. this._max = 0;
  10014. this._average = 0;
  10015. this._lastSecAverage = 0;
  10016. this._current = 0;
  10017. this._totalValueCount = 0;
  10018. this._totalAccumulated = 0;
  10019. this._lastSecAccumulated = 0;
  10020. this._lastSecTime = 0;
  10021. this._lastSecValueCount = 0;
  10022. }
  10023. Object.defineProperty(PerfCounter.prototype, "min", {
  10024. /**
  10025. * Returns the smallest value ever
  10026. */
  10027. get: function () {
  10028. return this._min;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(PerfCounter.prototype, "max", {
  10034. /**
  10035. * Returns the biggest value ever
  10036. */
  10037. get: function () {
  10038. return this._max;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(PerfCounter.prototype, "average", {
  10044. /**
  10045. * Returns the average value since the performance counter is running
  10046. */
  10047. get: function () {
  10048. return this._average;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10054. /**
  10055. * Returns the average value of the last second the counter was monitored
  10056. */
  10057. get: function () {
  10058. return this._lastSecAverage;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(PerfCounter.prototype, "current", {
  10064. /**
  10065. * Returns the current value
  10066. */
  10067. get: function () {
  10068. return this._current;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "total", {
  10074. get: function () {
  10075. return this._totalAccumulated;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. Object.defineProperty(PerfCounter.prototype, "count", {
  10081. get: function () {
  10082. return this._totalValueCount;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. /**
  10088. * Call this method to start monitoring a new frame.
  10089. * 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.
  10090. */
  10091. PerfCounter.prototype.fetchNewFrame = function () {
  10092. this._totalValueCount++;
  10093. this._current = 0;
  10094. this._lastSecValueCount++;
  10095. };
  10096. /**
  10097. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10098. * @param newCount the count value to add to the monitored count
  10099. * @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.
  10100. */
  10101. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10102. if (!PerfCounter.Enabled) {
  10103. return;
  10104. }
  10105. this._current += newCount;
  10106. if (fetchResult) {
  10107. this._fetchResult();
  10108. }
  10109. };
  10110. /**
  10111. * Start monitoring this performance counter
  10112. */
  10113. PerfCounter.prototype.beginMonitoring = function () {
  10114. if (!PerfCounter.Enabled) {
  10115. return;
  10116. }
  10117. this._startMonitoringTime = Tools.Now;
  10118. };
  10119. /**
  10120. * Compute the time lapsed since the previous beginMonitoring() call.
  10121. * @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
  10122. */
  10123. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10124. if (newFrame === void 0) { newFrame = true; }
  10125. if (!PerfCounter.Enabled) {
  10126. return;
  10127. }
  10128. if (newFrame) {
  10129. this.fetchNewFrame();
  10130. }
  10131. var currentTime = Tools.Now;
  10132. this._current = currentTime - this._startMonitoringTime;
  10133. if (newFrame) {
  10134. this._fetchResult();
  10135. }
  10136. };
  10137. PerfCounter.prototype._fetchResult = function () {
  10138. this._totalAccumulated += this._current;
  10139. this._lastSecAccumulated += this._current;
  10140. // Min/Max update
  10141. this._min = Math.min(this._min, this._current);
  10142. this._max = Math.max(this._max, this._current);
  10143. this._average = this._totalAccumulated / this._totalValueCount;
  10144. // Reset last sec?
  10145. var now = Tools.Now;
  10146. if ((now - this._lastSecTime) > 1000) {
  10147. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10148. this._lastSecTime = now;
  10149. this._lastSecAccumulated = 0;
  10150. this._lastSecValueCount = 0;
  10151. }
  10152. };
  10153. PerfCounter.Enabled = true;
  10154. return PerfCounter;
  10155. }());
  10156. BABYLON.PerfCounter = PerfCounter;
  10157. /**
  10158. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10159. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10160. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10161. * @param name The name of the class, case should be preserved
  10162. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10163. */
  10164. function className(name, module) {
  10165. return function (target) {
  10166. target["__bjsclassName__"] = name;
  10167. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10168. };
  10169. }
  10170. BABYLON.className = className;
  10171. /**
  10172. * An implementation of a loop for asynchronous functions.
  10173. */
  10174. var AsyncLoop = /** @class */ (function () {
  10175. /**
  10176. * Constroctor.
  10177. * @param iterations the number of iterations.
  10178. * @param _fn the function to run each iteration
  10179. * @param _successCallback the callback that will be called upon succesful execution
  10180. * @param offset starting offset.
  10181. */
  10182. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10183. if (offset === void 0) { offset = 0; }
  10184. this.iterations = iterations;
  10185. this._fn = _fn;
  10186. this._successCallback = _successCallback;
  10187. this.index = offset - 1;
  10188. this._done = false;
  10189. }
  10190. /**
  10191. * Execute the next iteration. Must be called after the last iteration was finished.
  10192. */
  10193. AsyncLoop.prototype.executeNext = function () {
  10194. if (!this._done) {
  10195. if (this.index + 1 < this.iterations) {
  10196. ++this.index;
  10197. this._fn(this);
  10198. }
  10199. else {
  10200. this.breakLoop();
  10201. }
  10202. }
  10203. };
  10204. /**
  10205. * Break the loop and run the success callback.
  10206. */
  10207. AsyncLoop.prototype.breakLoop = function () {
  10208. this._done = true;
  10209. this._successCallback();
  10210. };
  10211. /**
  10212. * Helper function
  10213. */
  10214. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10215. if (offset === void 0) { offset = 0; }
  10216. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10217. loop.executeNext();
  10218. return loop;
  10219. };
  10220. /**
  10221. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10222. * @param iterations total number of iterations
  10223. * @param syncedIterations number of synchronous iterations in each async iteration.
  10224. * @param fn the function to call each iteration.
  10225. * @param callback a success call back that will be called when iterating stops.
  10226. * @param breakFunction a break condition (optional)
  10227. * @param timeout timeout settings for the setTimeout function. default - 0.
  10228. * @constructor
  10229. */
  10230. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10231. if (timeout === void 0) { timeout = 0; }
  10232. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10233. if (breakFunction && breakFunction())
  10234. loop.breakLoop();
  10235. else {
  10236. setTimeout(function () {
  10237. for (var i = 0; i < syncedIterations; ++i) {
  10238. var iteration = (loop.index * syncedIterations) + i;
  10239. if (iteration >= iterations)
  10240. break;
  10241. fn(iteration);
  10242. if (breakFunction && breakFunction()) {
  10243. loop.breakLoop();
  10244. break;
  10245. }
  10246. }
  10247. loop.executeNext();
  10248. }, timeout);
  10249. }
  10250. }, callback);
  10251. };
  10252. return AsyncLoop;
  10253. }());
  10254. BABYLON.AsyncLoop = AsyncLoop;
  10255. })(BABYLON || (BABYLON = {}));
  10256. //# sourceMappingURL=babylon.tools.js.map
  10257. var BABYLON;
  10258. (function (BABYLON) {
  10259. var PromiseStates;
  10260. (function (PromiseStates) {
  10261. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10262. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10263. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10264. })(PromiseStates || (PromiseStates = {}));
  10265. var FulFillmentAgregator = /** @class */ (function () {
  10266. function FulFillmentAgregator() {
  10267. this.count = 0;
  10268. this.target = 0;
  10269. this.results = [];
  10270. }
  10271. return FulFillmentAgregator;
  10272. }());
  10273. var InternalPromise = /** @class */ (function () {
  10274. function InternalPromise(resolver) {
  10275. var _this = this;
  10276. this._state = PromiseStates.Pending;
  10277. this._children = new Array();
  10278. this._rejectWasConsumed = false;
  10279. if (!resolver) {
  10280. return;
  10281. }
  10282. try {
  10283. resolver(function (value) {
  10284. _this._resolve(value);
  10285. }, function (reason) {
  10286. _this._reject(reason);
  10287. });
  10288. }
  10289. catch (e) {
  10290. this._reject(e);
  10291. }
  10292. }
  10293. Object.defineProperty(InternalPromise.prototype, "_result", {
  10294. get: function () {
  10295. return this._resultValue;
  10296. },
  10297. set: function (value) {
  10298. this._resultValue = value;
  10299. if (this._parent && this._parent._result === undefined) {
  10300. this._parent._result = value;
  10301. }
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. InternalPromise.prototype.catch = function (onRejected) {
  10307. return this.then(undefined, onRejected);
  10308. };
  10309. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10310. var _this = this;
  10311. var newPromise = new InternalPromise();
  10312. newPromise._onFulfilled = onFulfilled;
  10313. newPromise._onRejected = onRejected;
  10314. // Composition
  10315. this._children.push(newPromise);
  10316. newPromise._parent = this;
  10317. if (this._state !== PromiseStates.Pending) {
  10318. BABYLON.Tools.SetImmediate(function () {
  10319. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10320. var returnedValue = newPromise._resolve(_this._result);
  10321. if (returnedValue !== undefined && returnedValue !== null) {
  10322. if (returnedValue._state !== undefined) {
  10323. var returnedPromise = returnedValue;
  10324. newPromise._children.push(returnedPromise);
  10325. returnedPromise._parent = newPromise;
  10326. newPromise = returnedPromise;
  10327. }
  10328. else {
  10329. newPromise._result = returnedValue;
  10330. }
  10331. }
  10332. }
  10333. else {
  10334. newPromise._reject(_this._reason);
  10335. }
  10336. });
  10337. }
  10338. return newPromise;
  10339. };
  10340. InternalPromise.prototype._moveChildren = function (children) {
  10341. var _this = this;
  10342. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10343. this._children.forEach(function (child) {
  10344. child._parent = _this;
  10345. });
  10346. if (this._state === PromiseStates.Fulfilled) {
  10347. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10348. var child = _b[_i];
  10349. child._resolve(this._result);
  10350. }
  10351. }
  10352. else if (this._state === PromiseStates.Rejected) {
  10353. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10354. var child = _d[_c];
  10355. child._reject(this._reason);
  10356. }
  10357. }
  10358. var _a;
  10359. };
  10360. InternalPromise.prototype._resolve = function (value) {
  10361. try {
  10362. this._state = PromiseStates.Fulfilled;
  10363. var returnedValue = null;
  10364. if (this._onFulfilled) {
  10365. returnedValue = this._onFulfilled(value);
  10366. }
  10367. if (returnedValue !== undefined && returnedValue !== null) {
  10368. if (returnedValue._state !== undefined) {
  10369. // Transmit children
  10370. var returnedPromise = returnedValue;
  10371. returnedPromise._parent = this;
  10372. returnedPromise._moveChildren(this._children);
  10373. value = returnedPromise._result;
  10374. }
  10375. else {
  10376. value = returnedValue;
  10377. }
  10378. }
  10379. this._result = value;
  10380. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10381. var child = _a[_i];
  10382. child._resolve(value);
  10383. }
  10384. this._children.length = 0;
  10385. delete this._onFulfilled;
  10386. delete this._onRejected;
  10387. }
  10388. catch (e) {
  10389. this._reject(e, true);
  10390. }
  10391. };
  10392. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10393. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10394. this._state = PromiseStates.Rejected;
  10395. this._reason = reason;
  10396. if (this._onRejected && !onLocalThrow) {
  10397. try {
  10398. this._onRejected(reason);
  10399. this._rejectWasConsumed = true;
  10400. }
  10401. catch (e) {
  10402. reason = e;
  10403. }
  10404. }
  10405. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10406. var child = _a[_i];
  10407. if (this._rejectWasConsumed) {
  10408. child._resolve(null);
  10409. }
  10410. else {
  10411. child._reject(reason);
  10412. }
  10413. }
  10414. this._children.length = 0;
  10415. delete this._onFulfilled;
  10416. delete this._onRejected;
  10417. };
  10418. InternalPromise.resolve = function (value) {
  10419. var newPromise = new InternalPromise();
  10420. newPromise._resolve(value);
  10421. return newPromise;
  10422. };
  10423. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10424. promise.then(function (value) {
  10425. agregator.results[index] = value;
  10426. agregator.count++;
  10427. if (agregator.count === agregator.target) {
  10428. agregator.rootPromise._resolve(agregator.results);
  10429. }
  10430. return null;
  10431. }, function (reason) {
  10432. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10433. agregator.rootPromise._reject(reason);
  10434. }
  10435. });
  10436. };
  10437. InternalPromise.all = function (promises) {
  10438. var newPromise = new InternalPromise();
  10439. var agregator = new FulFillmentAgregator();
  10440. agregator.target = promises.length;
  10441. agregator.rootPromise = newPromise;
  10442. if (promises.length) {
  10443. for (var index = 0; index < promises.length; index++) {
  10444. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10445. }
  10446. }
  10447. else {
  10448. newPromise._resolve([]);
  10449. }
  10450. return newPromise;
  10451. };
  10452. InternalPromise.race = function (promises) {
  10453. var newPromise = new InternalPromise();
  10454. if (promises.length) {
  10455. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10456. var promise = promises_1[_i];
  10457. promise.then(function (value) {
  10458. if (newPromise) {
  10459. newPromise._resolve(value);
  10460. newPromise = null;
  10461. }
  10462. return null;
  10463. }, function (reason) {
  10464. if (newPromise) {
  10465. newPromise._reject(reason);
  10466. newPromise = null;
  10467. }
  10468. });
  10469. }
  10470. }
  10471. return newPromise;
  10472. };
  10473. return InternalPromise;
  10474. }());
  10475. /**
  10476. * Helper class that provides a small promise polyfill
  10477. */
  10478. var PromisePolyfill = /** @class */ (function () {
  10479. function PromisePolyfill() {
  10480. }
  10481. /**
  10482. * Static function used to check if the polyfill is required
  10483. * If this is the case then the function will inject the polyfill to window.Promise
  10484. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10485. */
  10486. PromisePolyfill.Apply = function (force) {
  10487. if (force === void 0) { force = false; }
  10488. if (force || typeof Promise === 'undefined') {
  10489. var root = window;
  10490. root.Promise = InternalPromise;
  10491. }
  10492. };
  10493. return PromisePolyfill;
  10494. }());
  10495. BABYLON.PromisePolyfill = PromisePolyfill;
  10496. })(BABYLON || (BABYLON = {}));
  10497. //# sourceMappingURL=babylon.promise.js.map
  10498. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10499. var BABYLON;
  10500. (function (BABYLON) {
  10501. /**
  10502. * Helper class to push actions to a pool of workers.
  10503. */
  10504. var WorkerPool = /** @class */ (function () {
  10505. /**
  10506. * Constructor
  10507. * @param workers Array of workers to use for actions
  10508. */
  10509. function WorkerPool(workers) {
  10510. this._pendingActions = new Array();
  10511. this._workerInfos = workers.map(function (worker) { return ({
  10512. worker: worker,
  10513. active: false
  10514. }); });
  10515. }
  10516. /**
  10517. * Terminates all workers and clears any pending actions.
  10518. */
  10519. WorkerPool.prototype.dispose = function () {
  10520. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10521. var workerInfo = _a[_i];
  10522. workerInfo.worker.terminate();
  10523. }
  10524. delete this._workerInfos;
  10525. delete this._pendingActions;
  10526. };
  10527. /**
  10528. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10529. * pended until a worker has completed its action.
  10530. * @param action The action to perform. Call onComplete when the action is complete.
  10531. */
  10532. WorkerPool.prototype.push = function (action) {
  10533. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10534. var workerInfo = _a[_i];
  10535. if (!workerInfo.active) {
  10536. this._execute(workerInfo, action);
  10537. return;
  10538. }
  10539. }
  10540. this._pendingActions.push(action);
  10541. };
  10542. WorkerPool.prototype._execute = function (workerInfo, action) {
  10543. var _this = this;
  10544. workerInfo.active = true;
  10545. action(workerInfo.worker, function () {
  10546. workerInfo.active = false;
  10547. var nextAction = _this._pendingActions.shift();
  10548. if (nextAction) {
  10549. _this._execute(workerInfo, nextAction);
  10550. }
  10551. });
  10552. };
  10553. return WorkerPool;
  10554. }());
  10555. BABYLON.WorkerPool = WorkerPool;
  10556. })(BABYLON || (BABYLON = {}));
  10557. //# sourceMappingURL=babylon.workerPool.js.map
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. /**
  10561. * @hidden
  10562. **/
  10563. var _AlphaState = /** @class */ (function () {
  10564. /**
  10565. * Initializes the state.
  10566. */
  10567. function _AlphaState() {
  10568. this._isAlphaBlendDirty = false;
  10569. this._isBlendFunctionParametersDirty = false;
  10570. this._isBlendEquationParametersDirty = false;
  10571. this._isBlendConstantsDirty = false;
  10572. this._alphaBlend = false;
  10573. this._blendFunctionParameters = new Array(4);
  10574. this._blendEquationParameters = new Array(2);
  10575. this._blendConstants = new Array(4);
  10576. this.reset();
  10577. }
  10578. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10579. get: function () {
  10580. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10586. get: function () {
  10587. return this._alphaBlend;
  10588. },
  10589. set: function (value) {
  10590. if (this._alphaBlend === value) {
  10591. return;
  10592. }
  10593. this._alphaBlend = value;
  10594. this._isAlphaBlendDirty = true;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10600. if (this._blendConstants[0] === r &&
  10601. this._blendConstants[1] === g &&
  10602. this._blendConstants[2] === b &&
  10603. this._blendConstants[3] === a) {
  10604. return;
  10605. }
  10606. this._blendConstants[0] = r;
  10607. this._blendConstants[1] = g;
  10608. this._blendConstants[2] = b;
  10609. this._blendConstants[3] = a;
  10610. this._isBlendConstantsDirty = true;
  10611. };
  10612. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10613. if (this._blendFunctionParameters[0] === value0 &&
  10614. this._blendFunctionParameters[1] === value1 &&
  10615. this._blendFunctionParameters[2] === value2 &&
  10616. this._blendFunctionParameters[3] === value3) {
  10617. return;
  10618. }
  10619. this._blendFunctionParameters[0] = value0;
  10620. this._blendFunctionParameters[1] = value1;
  10621. this._blendFunctionParameters[2] = value2;
  10622. this._blendFunctionParameters[3] = value3;
  10623. this._isBlendFunctionParametersDirty = true;
  10624. };
  10625. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10626. if (this._blendEquationParameters[0] === rgb &&
  10627. this._blendEquationParameters[1] === alpha) {
  10628. return;
  10629. }
  10630. this._blendEquationParameters[0] = rgb;
  10631. this._blendEquationParameters[1] = alpha;
  10632. this._isBlendEquationParametersDirty = true;
  10633. };
  10634. _AlphaState.prototype.reset = function () {
  10635. this._alphaBlend = false;
  10636. this._blendFunctionParameters[0] = null;
  10637. this._blendFunctionParameters[1] = null;
  10638. this._blendFunctionParameters[2] = null;
  10639. this._blendFunctionParameters[3] = null;
  10640. this._blendEquationParameters[0] = null;
  10641. this._blendEquationParameters[1] = null;
  10642. this._blendConstants[0] = null;
  10643. this._blendConstants[1] = null;
  10644. this._blendConstants[2] = null;
  10645. this._blendConstants[3] = null;
  10646. this._isAlphaBlendDirty = true;
  10647. this._isBlendFunctionParametersDirty = false;
  10648. this._isBlendEquationParametersDirty = false;
  10649. this._isBlendConstantsDirty = false;
  10650. };
  10651. _AlphaState.prototype.apply = function (gl) {
  10652. if (!this.isDirty) {
  10653. return;
  10654. }
  10655. // Alpha blend
  10656. if (this._isAlphaBlendDirty) {
  10657. if (this._alphaBlend) {
  10658. gl.enable(gl.BLEND);
  10659. }
  10660. else {
  10661. gl.disable(gl.BLEND);
  10662. }
  10663. this._isAlphaBlendDirty = false;
  10664. }
  10665. // Alpha function
  10666. if (this._isBlendFunctionParametersDirty) {
  10667. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10668. this._isBlendFunctionParametersDirty = false;
  10669. }
  10670. // Alpha equation
  10671. if (this._isBlendEquationParametersDirty) {
  10672. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10673. this._isBlendEquationParametersDirty = false;
  10674. }
  10675. // Constants
  10676. if (this._isBlendConstantsDirty) {
  10677. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10678. this._isBlendConstantsDirty = false;
  10679. }
  10680. };
  10681. return _AlphaState;
  10682. }());
  10683. BABYLON._AlphaState = _AlphaState;
  10684. })(BABYLON || (BABYLON = {}));
  10685. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10686. var BABYLON;
  10687. (function (BABYLON) {
  10688. /**
  10689. * @hidden
  10690. **/
  10691. var _DepthCullingState = /** @class */ (function () {
  10692. /**
  10693. * Initializes the state.
  10694. */
  10695. function _DepthCullingState() {
  10696. this._isDepthTestDirty = false;
  10697. this._isDepthMaskDirty = false;
  10698. this._isDepthFuncDirty = false;
  10699. this._isCullFaceDirty = false;
  10700. this._isCullDirty = false;
  10701. this._isZOffsetDirty = false;
  10702. this._isFrontFaceDirty = false;
  10703. this.reset();
  10704. }
  10705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10706. get: function () {
  10707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10713. get: function () {
  10714. return this._zOffset;
  10715. },
  10716. set: function (value) {
  10717. if (this._zOffset === value) {
  10718. return;
  10719. }
  10720. this._zOffset = value;
  10721. this._isZOffsetDirty = true;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10727. get: function () {
  10728. return this._cullFace;
  10729. },
  10730. set: function (value) {
  10731. if (this._cullFace === value) {
  10732. return;
  10733. }
  10734. this._cullFace = value;
  10735. this._isCullFaceDirty = true;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10741. get: function () {
  10742. return this._cull;
  10743. },
  10744. set: function (value) {
  10745. if (this._cull === value) {
  10746. return;
  10747. }
  10748. this._cull = value;
  10749. this._isCullDirty = true;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10755. get: function () {
  10756. return this._depthFunc;
  10757. },
  10758. set: function (value) {
  10759. if (this._depthFunc === value) {
  10760. return;
  10761. }
  10762. this._depthFunc = value;
  10763. this._isDepthFuncDirty = true;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10769. get: function () {
  10770. return this._depthMask;
  10771. },
  10772. set: function (value) {
  10773. if (this._depthMask === value) {
  10774. return;
  10775. }
  10776. this._depthMask = value;
  10777. this._isDepthMaskDirty = true;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10783. get: function () {
  10784. return this._depthTest;
  10785. },
  10786. set: function (value) {
  10787. if (this._depthTest === value) {
  10788. return;
  10789. }
  10790. this._depthTest = value;
  10791. this._isDepthTestDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10797. get: function () {
  10798. return this._frontFace;
  10799. },
  10800. set: function (value) {
  10801. if (this._frontFace === value) {
  10802. return;
  10803. }
  10804. this._frontFace = value;
  10805. this._isFrontFaceDirty = true;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. _DepthCullingState.prototype.reset = function () {
  10811. this._depthMask = true;
  10812. this._depthTest = true;
  10813. this._depthFunc = null;
  10814. this._cullFace = null;
  10815. this._cull = null;
  10816. this._zOffset = 0;
  10817. this._frontFace = null;
  10818. this._isDepthTestDirty = true;
  10819. this._isDepthMaskDirty = true;
  10820. this._isDepthFuncDirty = false;
  10821. this._isCullFaceDirty = false;
  10822. this._isCullDirty = false;
  10823. this._isZOffsetDirty = false;
  10824. this._isFrontFaceDirty = false;
  10825. };
  10826. _DepthCullingState.prototype.apply = function (gl) {
  10827. if (!this.isDirty) {
  10828. return;
  10829. }
  10830. // Cull
  10831. if (this._isCullDirty) {
  10832. if (this.cull) {
  10833. gl.enable(gl.CULL_FACE);
  10834. }
  10835. else {
  10836. gl.disable(gl.CULL_FACE);
  10837. }
  10838. this._isCullDirty = false;
  10839. }
  10840. // Cull face
  10841. if (this._isCullFaceDirty) {
  10842. gl.cullFace(this.cullFace);
  10843. this._isCullFaceDirty = false;
  10844. }
  10845. // Depth mask
  10846. if (this._isDepthMaskDirty) {
  10847. gl.depthMask(this.depthMask);
  10848. this._isDepthMaskDirty = false;
  10849. }
  10850. // Depth test
  10851. if (this._isDepthTestDirty) {
  10852. if (this.depthTest) {
  10853. gl.enable(gl.DEPTH_TEST);
  10854. }
  10855. else {
  10856. gl.disable(gl.DEPTH_TEST);
  10857. }
  10858. this._isDepthTestDirty = false;
  10859. }
  10860. // Depth func
  10861. if (this._isDepthFuncDirty) {
  10862. gl.depthFunc(this.depthFunc);
  10863. this._isDepthFuncDirty = false;
  10864. }
  10865. // zOffset
  10866. if (this._isZOffsetDirty) {
  10867. if (this.zOffset) {
  10868. gl.enable(gl.POLYGON_OFFSET_FILL);
  10869. gl.polygonOffset(this.zOffset, 0);
  10870. }
  10871. else {
  10872. gl.disable(gl.POLYGON_OFFSET_FILL);
  10873. }
  10874. this._isZOffsetDirty = false;
  10875. }
  10876. // Front face
  10877. if (this._isFrontFaceDirty) {
  10878. gl.frontFace(this.frontFace);
  10879. this._isFrontFaceDirty = false;
  10880. }
  10881. };
  10882. return _DepthCullingState;
  10883. }());
  10884. BABYLON._DepthCullingState = _DepthCullingState;
  10885. })(BABYLON || (BABYLON = {}));
  10886. //# sourceMappingURL=babylon.depthCullingState.js.map
  10887. var BABYLON;
  10888. (function (BABYLON) {
  10889. /**
  10890. * @hidden
  10891. **/
  10892. var _StencilState = /** @class */ (function () {
  10893. function _StencilState() {
  10894. this._isStencilTestDirty = false;
  10895. this._isStencilMaskDirty = false;
  10896. this._isStencilFuncDirty = false;
  10897. this._isStencilOpDirty = false;
  10898. this.reset();
  10899. }
  10900. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10901. get: function () {
  10902. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10903. },
  10904. enumerable: true,
  10905. configurable: true
  10906. });
  10907. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10908. get: function () {
  10909. return this._stencilFunc;
  10910. },
  10911. set: function (value) {
  10912. if (this._stencilFunc === value) {
  10913. return;
  10914. }
  10915. this._stencilFunc = value;
  10916. this._isStencilFuncDirty = true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10922. get: function () {
  10923. return this._stencilFuncRef;
  10924. },
  10925. set: function (value) {
  10926. if (this._stencilFuncRef === value) {
  10927. return;
  10928. }
  10929. this._stencilFuncRef = value;
  10930. this._isStencilFuncDirty = true;
  10931. },
  10932. enumerable: true,
  10933. configurable: true
  10934. });
  10935. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10936. get: function () {
  10937. return this._stencilFuncMask;
  10938. },
  10939. set: function (value) {
  10940. if (this._stencilFuncMask === value) {
  10941. return;
  10942. }
  10943. this._stencilFuncMask = value;
  10944. this._isStencilFuncDirty = true;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10950. get: function () {
  10951. return this._stencilOpStencilFail;
  10952. },
  10953. set: function (value) {
  10954. if (this._stencilOpStencilFail === value) {
  10955. return;
  10956. }
  10957. this._stencilOpStencilFail = value;
  10958. this._isStencilOpDirty = true;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10964. get: function () {
  10965. return this._stencilOpDepthFail;
  10966. },
  10967. set: function (value) {
  10968. if (this._stencilOpDepthFail === value) {
  10969. return;
  10970. }
  10971. this._stencilOpDepthFail = value;
  10972. this._isStencilOpDirty = true;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10978. get: function () {
  10979. return this._stencilOpStencilDepthPass;
  10980. },
  10981. set: function (value) {
  10982. if (this._stencilOpStencilDepthPass === value) {
  10983. return;
  10984. }
  10985. this._stencilOpStencilDepthPass = value;
  10986. this._isStencilOpDirty = true;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10992. get: function () {
  10993. return this._stencilMask;
  10994. },
  10995. set: function (value) {
  10996. if (this._stencilMask === value) {
  10997. return;
  10998. }
  10999. this._stencilMask = value;
  11000. this._isStencilMaskDirty = true;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11006. get: function () {
  11007. return this._stencilTest;
  11008. },
  11009. set: function (value) {
  11010. if (this._stencilTest === value) {
  11011. return;
  11012. }
  11013. this._stencilTest = value;
  11014. this._isStencilTestDirty = true;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. _StencilState.prototype.reset = function () {
  11020. this._stencilTest = false;
  11021. this._stencilMask = 0xFF;
  11022. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11023. this._stencilFuncRef = 1;
  11024. this._stencilFuncMask = 0xFF;
  11025. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11026. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11027. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11028. this._isStencilTestDirty = true;
  11029. this._isStencilMaskDirty = true;
  11030. this._isStencilFuncDirty = true;
  11031. this._isStencilOpDirty = true;
  11032. };
  11033. _StencilState.prototype.apply = function (gl) {
  11034. if (!this.isDirty) {
  11035. return;
  11036. }
  11037. // Stencil test
  11038. if (this._isStencilTestDirty) {
  11039. if (this.stencilTest) {
  11040. gl.enable(gl.STENCIL_TEST);
  11041. }
  11042. else {
  11043. gl.disable(gl.STENCIL_TEST);
  11044. }
  11045. this._isStencilTestDirty = false;
  11046. }
  11047. // Stencil mask
  11048. if (this._isStencilMaskDirty) {
  11049. gl.stencilMask(this.stencilMask);
  11050. this._isStencilMaskDirty = false;
  11051. }
  11052. // Stencil func
  11053. if (this._isStencilFuncDirty) {
  11054. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11055. this._isStencilFuncDirty = false;
  11056. }
  11057. // Stencil op
  11058. if (this._isStencilOpDirty) {
  11059. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11060. this._isStencilOpDirty = false;
  11061. }
  11062. };
  11063. return _StencilState;
  11064. }());
  11065. BABYLON._StencilState = _StencilState;
  11066. })(BABYLON || (BABYLON = {}));
  11067. //# sourceMappingURL=babylon.stencilState.js.map
  11068. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11069. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11070. s = arguments[i];
  11071. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11072. t[p] = s[p];
  11073. }
  11074. return t;
  11075. };
  11076. var BABYLON;
  11077. (function (BABYLON) {
  11078. /**
  11079. * Keeps track of all the buffer info used in engine.
  11080. */
  11081. var BufferPointer = /** @class */ (function () {
  11082. function BufferPointer() {
  11083. }
  11084. return BufferPointer;
  11085. }());
  11086. /**
  11087. * Interface for attribute information associated with buffer instanciation
  11088. */
  11089. var InstancingAttributeInfo = /** @class */ (function () {
  11090. function InstancingAttributeInfo() {
  11091. }
  11092. return InstancingAttributeInfo;
  11093. }());
  11094. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11095. /**
  11096. * Define options used to create a render target texture
  11097. */
  11098. var RenderTargetCreationOptions = /** @class */ (function () {
  11099. function RenderTargetCreationOptions() {
  11100. }
  11101. return RenderTargetCreationOptions;
  11102. }());
  11103. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11104. /**
  11105. * Define options used to create a depth texture
  11106. */
  11107. var DepthTextureCreationOptions = /** @class */ (function () {
  11108. function DepthTextureCreationOptions() {
  11109. }
  11110. return DepthTextureCreationOptions;
  11111. }());
  11112. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11113. /**
  11114. * Class used to describe the capabilities of the engine relatively to the current browser
  11115. */
  11116. var EngineCapabilities = /** @class */ (function () {
  11117. function EngineCapabilities() {
  11118. }
  11119. return EngineCapabilities;
  11120. }());
  11121. BABYLON.EngineCapabilities = EngineCapabilities;
  11122. /**
  11123. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11124. */
  11125. var Engine = /** @class */ (function () {
  11126. /**
  11127. * Creates a new engine
  11128. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11129. * @param antialias defines enable antialiasing (default: false)
  11130. * @param options defines further options to be sent to the getContext() function
  11131. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11132. */
  11133. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11134. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11135. var _this = this;
  11136. // Public members
  11137. /**
  11138. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11139. */
  11140. this.forcePOTTextures = false;
  11141. /**
  11142. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11143. */
  11144. this.isFullscreen = false;
  11145. /**
  11146. * Gets a boolean indicating if the pointer is currently locked
  11147. */
  11148. this.isPointerLock = false;
  11149. /**
  11150. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11151. */
  11152. this.cullBackFaces = true;
  11153. /**
  11154. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11155. */
  11156. this.renderEvenInBackground = true;
  11157. /**
  11158. * Gets or sets a boolean indicating that cache can be kept between frames
  11159. */
  11160. this.preventCacheWipeBetweenFrames = false;
  11161. /**
  11162. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11163. **/
  11164. this.enableOfflineSupport = false;
  11165. /**
  11166. * 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)
  11167. **/
  11168. this.disableManifestCheck = false;
  11169. /**
  11170. * Gets the list of created scenes
  11171. */
  11172. this.scenes = new Array();
  11173. /**
  11174. * Gets the list of created postprocesses
  11175. */
  11176. this.postProcesses = new Array();
  11177. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11178. this.validateShaderPrograms = false;
  11179. // Observables
  11180. /**
  11181. * Observable event triggered each time the rendering canvas is resized
  11182. */
  11183. this.onResizeObservable = new BABYLON.Observable();
  11184. /**
  11185. * Observable event triggered each time the canvas loses focus
  11186. */
  11187. this.onCanvasBlurObservable = new BABYLON.Observable();
  11188. /**
  11189. * Observable event triggered each time the canvas gains focus
  11190. */
  11191. this.onCanvasFocusObservable = new BABYLON.Observable();
  11192. /**
  11193. * Observable event triggered each time the canvas receives pointerout event
  11194. */
  11195. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11196. /**
  11197. * Observable event triggered before each texture is initialized
  11198. */
  11199. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11200. //WebVR
  11201. this._vrDisplay = undefined;
  11202. this._vrSupported = false;
  11203. this._vrExclusivePointerMode = false;
  11204. // Uniform buffers list
  11205. /**
  11206. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11207. */
  11208. this.disableUniformBuffers = false;
  11209. /** @hidden */
  11210. this._uniformBuffers = new Array();
  11211. // Observables
  11212. /**
  11213. * Observable raised when the engine begins a new frame
  11214. */
  11215. this.onBeginFrameObservable = new BABYLON.Observable();
  11216. /**
  11217. * Observable raised when the engine ends the current frame
  11218. */
  11219. this.onEndFrameObservable = new BABYLON.Observable();
  11220. /**
  11221. * Observable raised when the engine is about to compile a shader
  11222. */
  11223. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable raised when the engine has jsut compiled a shader
  11226. */
  11227. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11228. this._windowIsBackground = false;
  11229. this._webGLVersion = 1.0;
  11230. /** @hidden */
  11231. this._badOS = false;
  11232. /** @hidden */
  11233. this._badDesktopOS = false;
  11234. /**
  11235. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11236. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11237. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11238. */
  11239. this.disableTextureBindingOptimization = false;
  11240. /**
  11241. * Observable signaled when VR display mode changes
  11242. */
  11243. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11244. /**
  11245. * Observable signaled when VR request present is complete
  11246. */
  11247. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11248. /**
  11249. * Observable signaled when VR request present starts
  11250. */
  11251. this.onVRRequestPresentStart = new BABYLON.Observable();
  11252. this._colorWrite = true;
  11253. /** @hidden */
  11254. this._drawCalls = new BABYLON.PerfCounter();
  11255. /** @hidden */
  11256. this._textureCollisions = new BABYLON.PerfCounter();
  11257. this._renderingQueueLaunched = false;
  11258. this._activeRenderLoops = new Array();
  11259. // Deterministic lockstepMaxSteps
  11260. this._deterministicLockstep = false;
  11261. this._lockstepMaxSteps = 4;
  11262. // Lost context
  11263. /**
  11264. * Observable signaled when a context lost event is raised
  11265. */
  11266. this.onContextLostObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable signaled when a context restored event is raised
  11269. */
  11270. this.onContextRestoredObservable = new BABYLON.Observable();
  11271. this._contextWasLost = false;
  11272. this._doNotHandleContextLost = false;
  11273. // FPS
  11274. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11275. this._fps = 60;
  11276. this._deltaTime = 0;
  11277. /**
  11278. * Turn this value on if you want to pause FPS computation when in background
  11279. */
  11280. this.disablePerformanceMonitorInBackground = false;
  11281. // States
  11282. /** @hidden */
  11283. this._depthCullingState = new BABYLON._DepthCullingState();
  11284. /** @hidden */
  11285. this._stencilState = new BABYLON._StencilState();
  11286. /** @hidden */
  11287. this._alphaState = new BABYLON._AlphaState();
  11288. /** @hidden */
  11289. this._alphaMode = Engine.ALPHA_DISABLE;
  11290. // Cache
  11291. this._internalTexturesCache = new Array();
  11292. /** @hidden */
  11293. this._activeChannel = 0;
  11294. this._currentTextureChannel = -1;
  11295. /** @hidden */
  11296. this._boundTexturesCache = {};
  11297. this._compiledEffects = {};
  11298. this._vertexAttribArraysEnabled = [];
  11299. this._uintIndicesCurrentlySet = false;
  11300. this._currentBoundBuffer = new Array();
  11301. /** @hidden */
  11302. this._currentFramebuffer = null;
  11303. this._currentBufferPointers = new Array();
  11304. this._currentInstanceLocations = new Array();
  11305. this._currentInstanceBuffers = new Array();
  11306. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11307. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11308. this._vaoRecordInProgress = false;
  11309. this._mustWipeVertexAttributes = false;
  11310. this._nextFreeTextureSlots = new Array();
  11311. this._maxSimultaneousTextures = 0;
  11312. this._activeRequests = new Array();
  11313. // Hardware supported Compressed Textures
  11314. this._texturesSupported = new Array();
  11315. /**
  11316. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11317. */
  11318. this.premultipliedAlpha = true;
  11319. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11320. this._onVRFullScreenTriggered = function () {
  11321. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11322. //get the old size before we change
  11323. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11324. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11325. //get the width and height, change the render size
  11326. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11327. _this.setHardwareScalingLevel(1);
  11328. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11329. }
  11330. else {
  11331. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11332. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11333. }
  11334. };
  11335. this._unpackFlipYCached = null;
  11336. this._boundUniforms = {};
  11337. // Register promises
  11338. BABYLON.PromisePolyfill.Apply();
  11339. var canvas = null;
  11340. Engine.Instances.push(this);
  11341. if (!canvasOrContext) {
  11342. return;
  11343. }
  11344. options = options || {};
  11345. if (canvasOrContext.getContext) {
  11346. canvas = canvasOrContext;
  11347. this._renderingCanvas = canvas;
  11348. if (antialias != null) {
  11349. options.antialias = antialias;
  11350. }
  11351. if (options.deterministicLockstep === undefined) {
  11352. options.deterministicLockstep = false;
  11353. }
  11354. if (options.lockstepMaxSteps === undefined) {
  11355. options.lockstepMaxSteps = 4;
  11356. }
  11357. if (options.preserveDrawingBuffer === undefined) {
  11358. options.preserveDrawingBuffer = false;
  11359. }
  11360. if (options.audioEngine === undefined) {
  11361. options.audioEngine = true;
  11362. }
  11363. if (options.stencil === undefined) {
  11364. options.stencil = true;
  11365. }
  11366. if (options.premultipliedAlpha === false) {
  11367. this.premultipliedAlpha = false;
  11368. }
  11369. this._deterministicLockstep = options.deterministicLockstep;
  11370. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11371. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11372. // Exceptions
  11373. if (navigator && navigator.userAgent) {
  11374. var ua = navigator.userAgent;
  11375. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11376. var exception = _a[_i];
  11377. var key = exception.key;
  11378. var targets = exception.targets;
  11379. if (ua.indexOf(key) > -1) {
  11380. if (exception.capture && exception.captureConstraint) {
  11381. var capture = exception.capture;
  11382. var constraint = exception.captureConstraint;
  11383. var regex = new RegExp(capture);
  11384. var matches = regex.exec(ua);
  11385. if (matches && matches.length > 0) {
  11386. var capturedValue = parseInt(matches[matches.length - 1]);
  11387. if (capturedValue >= constraint) {
  11388. continue;
  11389. }
  11390. }
  11391. }
  11392. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11393. var target = targets_1[_b];
  11394. switch (target) {
  11395. case "uniformBuffer":
  11396. this.disableUniformBuffers = true;
  11397. break;
  11398. case "textureBindingOptimization":
  11399. this.disableTextureBindingOptimization = true;
  11400. break;
  11401. }
  11402. }
  11403. }
  11404. }
  11405. }
  11406. // GL
  11407. if (!options.disableWebGL2Support) {
  11408. try {
  11409. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11410. if (this._gl) {
  11411. this._webGLVersion = 2.0;
  11412. }
  11413. }
  11414. catch (e) {
  11415. // Do nothing
  11416. }
  11417. }
  11418. if (!this._gl) {
  11419. if (!canvas) {
  11420. throw new Error("The provided canvas is null or undefined.");
  11421. }
  11422. try {
  11423. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11424. }
  11425. catch (e) {
  11426. throw new Error("WebGL not supported");
  11427. }
  11428. }
  11429. if (!this._gl) {
  11430. throw new Error("WebGL not supported");
  11431. }
  11432. this._onCanvasFocus = function () {
  11433. _this.onCanvasFocusObservable.notifyObservers(_this);
  11434. };
  11435. this._onCanvasBlur = function () {
  11436. _this.onCanvasBlurObservable.notifyObservers(_this);
  11437. };
  11438. canvas.addEventListener("focus", this._onCanvasFocus);
  11439. canvas.addEventListener("blur", this._onCanvasBlur);
  11440. this._onBlur = function () {
  11441. if (_this.disablePerformanceMonitorInBackground) {
  11442. _this._performanceMonitor.disable();
  11443. }
  11444. _this._windowIsBackground = true;
  11445. };
  11446. this._onFocus = function () {
  11447. if (_this.disablePerformanceMonitorInBackground) {
  11448. _this._performanceMonitor.enable();
  11449. }
  11450. _this._windowIsBackground = false;
  11451. };
  11452. this._onCanvasPointerOut = function (ev) {
  11453. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11454. };
  11455. window.addEventListener("blur", this._onBlur);
  11456. window.addEventListener("focus", this._onFocus);
  11457. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11458. // Context lost
  11459. if (!this._doNotHandleContextLost) {
  11460. this._onContextLost = function (evt) {
  11461. evt.preventDefault();
  11462. _this._contextWasLost = true;
  11463. BABYLON.Tools.Warn("WebGL context lost.");
  11464. _this.onContextLostObservable.notifyObservers(_this);
  11465. };
  11466. this._onContextRestored = function (evt) {
  11467. // Adding a timeout to avoid race condition at browser level
  11468. setTimeout(function () {
  11469. // Rebuild gl context
  11470. _this._initGLContext();
  11471. // Rebuild effects
  11472. _this._rebuildEffects();
  11473. // Rebuild textures
  11474. _this._rebuildInternalTextures();
  11475. // Rebuild buffers
  11476. _this._rebuildBuffers();
  11477. // Cache
  11478. _this.wipeCaches(true);
  11479. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11480. _this.onContextRestoredObservable.notifyObservers(_this);
  11481. _this._contextWasLost = false;
  11482. }, 0);
  11483. };
  11484. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11485. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11486. }
  11487. }
  11488. else {
  11489. this._gl = canvasOrContext;
  11490. this._renderingCanvas = this._gl.canvas;
  11491. if (this._gl.renderbufferStorageMultisample) {
  11492. this._webGLVersion = 2.0;
  11493. }
  11494. options.stencil = this._gl.getContextAttributes().stencil;
  11495. }
  11496. // Viewport
  11497. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11498. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11499. this.resize();
  11500. this._isStencilEnable = options.stencil ? true : false;
  11501. this._initGLContext();
  11502. if (canvas) {
  11503. // Fullscreen
  11504. this._onFullscreenChange = function () {
  11505. if (document.fullscreen !== undefined) {
  11506. _this.isFullscreen = document.fullscreen;
  11507. }
  11508. else if (document.mozFullScreen !== undefined) {
  11509. _this.isFullscreen = document.mozFullScreen;
  11510. }
  11511. else if (document.webkitIsFullScreen !== undefined) {
  11512. _this.isFullscreen = document.webkitIsFullScreen;
  11513. }
  11514. else if (document.msIsFullScreen !== undefined) {
  11515. _this.isFullscreen = document.msIsFullScreen;
  11516. }
  11517. // Pointer lock
  11518. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11519. canvas.requestPointerLock = canvas.requestPointerLock ||
  11520. canvas.msRequestPointerLock ||
  11521. canvas.mozRequestPointerLock ||
  11522. canvas.webkitRequestPointerLock;
  11523. if (canvas.requestPointerLock) {
  11524. canvas.requestPointerLock();
  11525. }
  11526. }
  11527. };
  11528. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11529. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11530. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11531. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11532. // Pointer lock
  11533. this._onPointerLockChange = function () {
  11534. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11535. document.webkitPointerLockElement === canvas ||
  11536. document.msPointerLockElement === canvas ||
  11537. document.pointerLockElement === canvas);
  11538. };
  11539. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11540. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11541. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11542. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11543. this._onVRDisplayPointerRestricted = function () {
  11544. if (canvas) {
  11545. canvas.requestPointerLock();
  11546. }
  11547. };
  11548. this._onVRDisplayPointerUnrestricted = function () {
  11549. document.exitPointerLock();
  11550. };
  11551. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11552. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11553. }
  11554. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11555. Engine.audioEngine = new BABYLON.AudioEngine();
  11556. }
  11557. // Prepare buffer pointers
  11558. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11559. this._currentBufferPointers[i] = new BufferPointer();
  11560. }
  11561. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11562. // Load WebVR Devices
  11563. if (options.autoEnableWebVR) {
  11564. this.initWebVR();
  11565. }
  11566. // Detect if we are running on a faulty buggy OS.
  11567. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11568. // Detect if we are running on a faulty buggy desktop OS.
  11569. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11570. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11571. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11572. }
  11573. Object.defineProperty(Engine, "LastCreatedEngine", {
  11574. /**
  11575. * Gets the latest created engine
  11576. */
  11577. get: function () {
  11578. if (Engine.Instances.length === 0) {
  11579. return null;
  11580. }
  11581. return Engine.Instances[Engine.Instances.length - 1];
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(Engine, "LastCreatedScene", {
  11587. /**
  11588. * Gets the latest created scene
  11589. */
  11590. get: function () {
  11591. var lastCreatedEngine = Engine.LastCreatedEngine;
  11592. if (!lastCreatedEngine) {
  11593. return null;
  11594. }
  11595. if (lastCreatedEngine.scenes.length === 0) {
  11596. return null;
  11597. }
  11598. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. /**
  11604. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11605. * @param flag defines which part of the materials must be marked as dirty
  11606. * @param predicate defines a predicate used to filter which materials should be affected
  11607. */
  11608. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11609. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11610. var engine = Engine.Instances[engineIndex];
  11611. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11612. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11613. }
  11614. }
  11615. };
  11616. Object.defineProperty(Engine, "Version", {
  11617. /**
  11618. * Returns the current version of the framework
  11619. */
  11620. get: function () {
  11621. return "3.3.0-alpha.11";
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11627. /**
  11628. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11629. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11630. */
  11631. get: function () {
  11632. return this._vrExclusivePointerMode;
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11638. /**
  11639. * Gets a boolean indicating that the engine supports uniform buffers
  11640. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11641. */
  11642. get: function () {
  11643. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11649. /**
  11650. * Gets a boolean indicating that only power of 2 textures are supported
  11651. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11652. */
  11653. get: function () {
  11654. return this._webGLVersion < 2 || this.forcePOTTextures;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11660. /**
  11661. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11662. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11663. */
  11664. get: function () {
  11665. return this._doNotHandleContextLost;
  11666. },
  11667. set: function (value) {
  11668. this._doNotHandleContextLost = value;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11674. /**
  11675. * Gets the performance monitor attached to this engine
  11676. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11677. */
  11678. get: function () {
  11679. return this._performanceMonitor;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11685. /**
  11686. * Gets the list of texture formats supported
  11687. */
  11688. get: function () {
  11689. return this._texturesSupported;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11695. /**
  11696. * Gets the list of texture formats in use
  11697. */
  11698. get: function () {
  11699. return this._textureFormatInUse;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine.prototype, "currentViewport", {
  11705. /**
  11706. * Gets the current viewport
  11707. */
  11708. get: function () {
  11709. return this._cachedViewport;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11715. /**
  11716. * Gets the default empty texture
  11717. */
  11718. get: function () {
  11719. if (!this._emptyTexture) {
  11720. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11721. }
  11722. return this._emptyTexture;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11728. /**
  11729. * Gets the default empty 3D texture
  11730. */
  11731. get: function () {
  11732. if (!this._emptyTexture3D) {
  11733. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11734. }
  11735. return this._emptyTexture3D;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11741. /**
  11742. * Gets the default empty cube texture
  11743. */
  11744. get: function () {
  11745. if (!this._emptyCubeTexture) {
  11746. var faceData = new Uint8Array(4);
  11747. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11748. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11749. }
  11750. return this._emptyCubeTexture;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Engine.prototype._rebuildInternalTextures = function () {
  11756. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11757. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11758. var internalTexture = currentState_1[_i];
  11759. internalTexture._rebuild();
  11760. }
  11761. };
  11762. Engine.prototype._rebuildEffects = function () {
  11763. for (var key in this._compiledEffects) {
  11764. var effect = this._compiledEffects[key];
  11765. effect._prepareEffect();
  11766. }
  11767. BABYLON.Effect.ResetCache();
  11768. };
  11769. Engine.prototype._rebuildBuffers = function () {
  11770. // Index / Vertex
  11771. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11772. var scene = _a[_i];
  11773. scene.resetCachedMaterial();
  11774. scene._rebuildGeometries();
  11775. scene._rebuildTextures();
  11776. }
  11777. // Uniforms
  11778. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11779. var uniformBuffer = _c[_b];
  11780. uniformBuffer._rebuild();
  11781. }
  11782. };
  11783. Engine.prototype._initGLContext = function () {
  11784. // Caps
  11785. this._caps = new EngineCapabilities();
  11786. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11787. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11788. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11789. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11790. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11791. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11792. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11793. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11794. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11795. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11796. // Infos
  11797. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11798. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11799. if (rendererInfo != null) {
  11800. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11801. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11802. }
  11803. if (!this._glVendor) {
  11804. this._glVendor = "Unknown vendor";
  11805. }
  11806. if (!this._glRenderer) {
  11807. this._glRenderer = "Unknown renderer";
  11808. }
  11809. // Constants
  11810. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11811. if (this._gl.RGBA16F !== 0x881A) {
  11812. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11813. }
  11814. if (this._gl.RGBA32F !== 0x8814) {
  11815. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11816. }
  11817. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11818. this._gl.DEPTH24_STENCIL8 = 35056;
  11819. }
  11820. // Extensions
  11821. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11822. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11823. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11824. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11825. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11826. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11827. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11828. 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');
  11829. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11830. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11831. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11832. this._caps.highPrecisionShaderSupported = true;
  11833. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11834. if (this._caps.timerQuery) {
  11835. if (this._webGLVersion === 1) {
  11836. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11837. }
  11838. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11839. }
  11840. // Checks if some of the format renders first to allow the use of webgl inspector.
  11841. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11842. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11843. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11844. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11845. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11846. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11847. if (this._webGLVersion > 1) {
  11848. this._gl.HALF_FLOAT_OES = 0x140B;
  11849. }
  11850. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11851. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11852. // Draw buffers
  11853. if (this._webGLVersion > 1) {
  11854. this._caps.drawBuffersExtension = true;
  11855. }
  11856. else {
  11857. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11858. if (drawBuffersExtension !== null) {
  11859. this._caps.drawBuffersExtension = true;
  11860. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11861. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11862. for (var i = 0; i < 16; i++) {
  11863. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11864. }
  11865. }
  11866. else {
  11867. this._caps.drawBuffersExtension = false;
  11868. }
  11869. }
  11870. // Depth Texture
  11871. if (this._webGLVersion > 1) {
  11872. this._caps.depthTextureExtension = true;
  11873. }
  11874. else {
  11875. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11876. if (depthTextureExtension != null) {
  11877. this._caps.depthTextureExtension = true;
  11878. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11879. }
  11880. }
  11881. // Vertex array object
  11882. if (this._webGLVersion > 1) {
  11883. this._caps.vertexArrayObject = true;
  11884. }
  11885. else {
  11886. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11887. if (vertexArrayObjectExtension != null) {
  11888. this._caps.vertexArrayObject = true;
  11889. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11890. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11891. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11892. }
  11893. else {
  11894. this._caps.vertexArrayObject = false;
  11895. }
  11896. }
  11897. // Instances count
  11898. if (this._webGLVersion > 1) {
  11899. this._caps.instancedArrays = true;
  11900. }
  11901. else {
  11902. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11903. if (instanceExtension != null) {
  11904. this._caps.instancedArrays = true;
  11905. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11906. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11907. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11908. }
  11909. else {
  11910. this._caps.instancedArrays = false;
  11911. }
  11912. }
  11913. // Intelligently add supported compressed formats in order to check for.
  11914. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11915. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11916. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11917. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11918. if (this._caps.astc)
  11919. this.texturesSupported.push('-astc.ktx');
  11920. if (this._caps.s3tc)
  11921. this.texturesSupported.push('-dxt.ktx');
  11922. if (this._caps.pvrtc)
  11923. this.texturesSupported.push('-pvrtc.ktx');
  11924. if (this._caps.etc2)
  11925. this.texturesSupported.push('-etc2.ktx');
  11926. if (this._caps.etc1)
  11927. this.texturesSupported.push('-etc1.ktx');
  11928. if (this._gl.getShaderPrecisionFormat) {
  11929. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11930. if (highp) {
  11931. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11932. }
  11933. }
  11934. // Depth buffer
  11935. this.setDepthBuffer(true);
  11936. this.setDepthFunctionToLessOrEqual();
  11937. this.setDepthWrite(true);
  11938. // Texture maps
  11939. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11940. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11941. this._nextFreeTextureSlots.push(slot);
  11942. }
  11943. };
  11944. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11945. /**
  11946. * Gets version of the current webGL context
  11947. */
  11948. get: function () {
  11949. return this._webGLVersion;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11955. /**
  11956. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11957. */
  11958. get: function () {
  11959. return this._isStencilEnable;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Engine.prototype._prepareWorkingCanvas = function () {
  11965. if (this._workingCanvas) {
  11966. return;
  11967. }
  11968. this._workingCanvas = document.createElement("canvas");
  11969. var context = this._workingCanvas.getContext("2d");
  11970. if (context) {
  11971. this._workingContext = context;
  11972. }
  11973. };
  11974. /**
  11975. * Reset the texture cache to empty state
  11976. */
  11977. Engine.prototype.resetTextureCache = function () {
  11978. for (var key in this._boundTexturesCache) {
  11979. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  11980. continue;
  11981. }
  11982. var boundTexture = this._boundTexturesCache[key];
  11983. if (boundTexture) {
  11984. this._removeDesignatedSlot(boundTexture);
  11985. }
  11986. this._boundTexturesCache[key] = null;
  11987. }
  11988. if (!this.disableTextureBindingOptimization) {
  11989. this._nextFreeTextureSlots = [];
  11990. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11991. this._nextFreeTextureSlots.push(slot);
  11992. }
  11993. }
  11994. this._currentTextureChannel = -1;
  11995. };
  11996. /**
  11997. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11998. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11999. * @returns true if engine is in deterministic lock step mode
  12000. */
  12001. Engine.prototype.isDeterministicLockStep = function () {
  12002. return this._deterministicLockstep;
  12003. };
  12004. /**
  12005. * Gets the max steps when engine is running in deterministic lock step
  12006. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12007. * @returns the max steps
  12008. */
  12009. Engine.prototype.getLockstepMaxSteps = function () {
  12010. return this._lockstepMaxSteps;
  12011. };
  12012. /**
  12013. * Gets an object containing information about the current webGL context
  12014. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12015. */
  12016. Engine.prototype.getGlInfo = function () {
  12017. return {
  12018. vendor: this._glVendor,
  12019. renderer: this._glRenderer,
  12020. version: this._glVersion
  12021. };
  12022. };
  12023. /**
  12024. * Gets current aspect ratio
  12025. * @param camera defines the camera to use to get the aspect ratio
  12026. * @param useScreen defines if screen size must be used (or the current render target if any)
  12027. * @returns a number defining the aspect ratio
  12028. */
  12029. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12030. if (useScreen === void 0) { useScreen = false; }
  12031. var viewport = camera.viewport;
  12032. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12033. };
  12034. /**
  12035. * Gets current screen aspect ratio
  12036. * @returns a number defining the aspect ratio
  12037. */
  12038. Engine.prototype.getScreenAspectRatio = function () {
  12039. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12040. };
  12041. /**
  12042. * Gets the current render width
  12043. * @param useScreen defines if screen size must be used (or the current render target if any)
  12044. * @returns a number defining the current render width
  12045. */
  12046. Engine.prototype.getRenderWidth = function (useScreen) {
  12047. if (useScreen === void 0) { useScreen = false; }
  12048. if (!useScreen && this._currentRenderTarget) {
  12049. return this._currentRenderTarget.width;
  12050. }
  12051. return this._gl.drawingBufferWidth;
  12052. };
  12053. /**
  12054. * Gets the current render height
  12055. * @param useScreen defines if screen size must be used (or the current render target if any)
  12056. * @returns a number defining the current render height
  12057. */
  12058. Engine.prototype.getRenderHeight = function (useScreen) {
  12059. if (useScreen === void 0) { useScreen = false; }
  12060. if (!useScreen && this._currentRenderTarget) {
  12061. return this._currentRenderTarget.height;
  12062. }
  12063. return this._gl.drawingBufferHeight;
  12064. };
  12065. /**
  12066. * Gets the HTML canvas attached with the current webGL context
  12067. * @returns a HTML canvas
  12068. */
  12069. Engine.prototype.getRenderingCanvas = function () {
  12070. return this._renderingCanvas;
  12071. };
  12072. /**
  12073. * Gets the client rect of the HTML canvas attached with the current webGL context
  12074. * @returns a client rectanglee
  12075. */
  12076. Engine.prototype.getRenderingCanvasClientRect = function () {
  12077. if (!this._renderingCanvas) {
  12078. return null;
  12079. }
  12080. return this._renderingCanvas.getBoundingClientRect();
  12081. };
  12082. /**
  12083. * Defines the hardware scaling level.
  12084. * By default the hardware scaling level is computed from the window device ratio.
  12085. * 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.
  12086. * @param level defines the level to use
  12087. */
  12088. Engine.prototype.setHardwareScalingLevel = function (level) {
  12089. this._hardwareScalingLevel = level;
  12090. this.resize();
  12091. };
  12092. /**
  12093. * Gets the current hardware scaling level.
  12094. * By default the hardware scaling level is computed from the window device ratio.
  12095. * 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.
  12096. * @returns a number indicating the current hardware scaling level
  12097. */
  12098. Engine.prototype.getHardwareScalingLevel = function () {
  12099. return this._hardwareScalingLevel;
  12100. };
  12101. /**
  12102. * Gets the list of loaded textures
  12103. * @returns an array containing all loaded textures
  12104. */
  12105. Engine.prototype.getLoadedTexturesCache = function () {
  12106. return this._internalTexturesCache;
  12107. };
  12108. /**
  12109. * Gets the object containing all engine capabilities
  12110. * @returns the EngineCapabilities object
  12111. */
  12112. Engine.prototype.getCaps = function () {
  12113. return this._caps;
  12114. };
  12115. Object.defineProperty(Engine.prototype, "drawCalls", {
  12116. /** @hidden */
  12117. get: function () {
  12118. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12119. return 0;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12125. /** @hidden */
  12126. get: function () {
  12127. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12128. return null;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. /**
  12134. * Gets the current depth function
  12135. * @returns a number defining the depth function
  12136. */
  12137. Engine.prototype.getDepthFunction = function () {
  12138. return this._depthCullingState.depthFunc;
  12139. };
  12140. /**
  12141. * Sets the current depth function
  12142. * @param depthFunc defines the function to use
  12143. */
  12144. Engine.prototype.setDepthFunction = function (depthFunc) {
  12145. this._depthCullingState.depthFunc = depthFunc;
  12146. };
  12147. /**
  12148. * Sets the current depth function to GREATER
  12149. */
  12150. Engine.prototype.setDepthFunctionToGreater = function () {
  12151. this._depthCullingState.depthFunc = this._gl.GREATER;
  12152. };
  12153. /**
  12154. * Sets the current depth function to GEQUAL
  12155. */
  12156. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12157. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12158. };
  12159. /**
  12160. * Sets the current depth function to LESS
  12161. */
  12162. Engine.prototype.setDepthFunctionToLess = function () {
  12163. this._depthCullingState.depthFunc = this._gl.LESS;
  12164. };
  12165. /**
  12166. * Sets the current depth function to LEQUAL
  12167. */
  12168. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12169. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12170. };
  12171. /**
  12172. * Gets a boolean indicating if stencil buffer is enabled
  12173. * @returns the current stencil buffer state
  12174. */
  12175. Engine.prototype.getStencilBuffer = function () {
  12176. return this._stencilState.stencilTest;
  12177. };
  12178. /**
  12179. * Enable or disable the stencil buffer
  12180. * @param enable defines if the stencil buffer must be enabled or disabled
  12181. */
  12182. Engine.prototype.setStencilBuffer = function (enable) {
  12183. this._stencilState.stencilTest = enable;
  12184. };
  12185. /**
  12186. * Gets the current stencil mask
  12187. * @returns a number defining the new stencil mask to use
  12188. */
  12189. Engine.prototype.getStencilMask = function () {
  12190. return this._stencilState.stencilMask;
  12191. };
  12192. /**
  12193. * Sets the current stencil mask
  12194. * @param mask defines the new stencil mask to use
  12195. */
  12196. Engine.prototype.setStencilMask = function (mask) {
  12197. this._stencilState.stencilMask = mask;
  12198. };
  12199. /**
  12200. * Gets the current stencil function
  12201. * @returns a number defining the stencil function to use
  12202. */
  12203. Engine.prototype.getStencilFunction = function () {
  12204. return this._stencilState.stencilFunc;
  12205. };
  12206. /**
  12207. * Gets the current stencil reference value
  12208. * @returns a number defining the stencil reference value to use
  12209. */
  12210. Engine.prototype.getStencilFunctionReference = function () {
  12211. return this._stencilState.stencilFuncRef;
  12212. };
  12213. /**
  12214. * Gets the current stencil mask
  12215. * @returns a number defining the stencil mask to use
  12216. */
  12217. Engine.prototype.getStencilFunctionMask = function () {
  12218. return this._stencilState.stencilFuncMask;
  12219. };
  12220. /**
  12221. * Sets the current stencil function
  12222. * @param stencilFunc defines the new stencil function to use
  12223. */
  12224. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12225. this._stencilState.stencilFunc = stencilFunc;
  12226. };
  12227. /**
  12228. * Sets the current stencil reference
  12229. * @param reference defines the new stencil reference to use
  12230. */
  12231. Engine.prototype.setStencilFunctionReference = function (reference) {
  12232. this._stencilState.stencilFuncRef = reference;
  12233. };
  12234. /**
  12235. * Sets the current stencil mask
  12236. * @param mask defines the new stencil mask to use
  12237. */
  12238. Engine.prototype.setStencilFunctionMask = function (mask) {
  12239. this._stencilState.stencilFuncMask = mask;
  12240. };
  12241. /**
  12242. * Gets the current stencil operation when stencil fails
  12243. * @returns a number defining stencil operation to use when stencil fails
  12244. */
  12245. Engine.prototype.getStencilOperationFail = function () {
  12246. return this._stencilState.stencilOpStencilFail;
  12247. };
  12248. /**
  12249. * Gets the current stencil operation when depth fails
  12250. * @returns a number defining stencil operation to use when depth fails
  12251. */
  12252. Engine.prototype.getStencilOperationDepthFail = function () {
  12253. return this._stencilState.stencilOpDepthFail;
  12254. };
  12255. /**
  12256. * Gets the current stencil operation when stencil passes
  12257. * @returns a number defining stencil operation to use when stencil passes
  12258. */
  12259. Engine.prototype.getStencilOperationPass = function () {
  12260. return this._stencilState.stencilOpStencilDepthPass;
  12261. };
  12262. /**
  12263. * Sets the stencil operation to use when stencil fails
  12264. * @param operation defines the stencil operation to use when stencil fails
  12265. */
  12266. Engine.prototype.setStencilOperationFail = function (operation) {
  12267. this._stencilState.stencilOpStencilFail = operation;
  12268. };
  12269. /**
  12270. * Sets the stencil operation to use when depth fails
  12271. * @param operation defines the stencil operation to use when depth fails
  12272. */
  12273. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12274. this._stencilState.stencilOpDepthFail = operation;
  12275. };
  12276. /**
  12277. * Sets the stencil operation to use when stencil passes
  12278. * @param operation defines the stencil operation to use when stencil passes
  12279. */
  12280. Engine.prototype.setStencilOperationPass = function (operation) {
  12281. this._stencilState.stencilOpStencilDepthPass = operation;
  12282. };
  12283. /**
  12284. * Sets a boolean indicating if the dithering state is enabled or disabled
  12285. * @param value defines the dithering state
  12286. */
  12287. Engine.prototype.setDitheringState = function (value) {
  12288. if (value) {
  12289. this._gl.enable(this._gl.DITHER);
  12290. }
  12291. else {
  12292. this._gl.disable(this._gl.DITHER);
  12293. }
  12294. };
  12295. /**
  12296. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12297. * @param value defines the rasterizer state
  12298. */
  12299. Engine.prototype.setRasterizerState = function (value) {
  12300. if (value) {
  12301. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12302. }
  12303. else {
  12304. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12305. }
  12306. };
  12307. /**
  12308. * stop executing a render loop function and remove it from the execution array
  12309. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12310. */
  12311. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12312. if (!renderFunction) {
  12313. this._activeRenderLoops = [];
  12314. return;
  12315. }
  12316. var index = this._activeRenderLoops.indexOf(renderFunction);
  12317. if (index >= 0) {
  12318. this._activeRenderLoops.splice(index, 1);
  12319. }
  12320. };
  12321. /** @hidden */
  12322. Engine.prototype._renderLoop = function () {
  12323. if (!this._contextWasLost) {
  12324. var shouldRender = true;
  12325. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12326. shouldRender = false;
  12327. }
  12328. if (shouldRender) {
  12329. // Start new frame
  12330. this.beginFrame();
  12331. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12332. var renderFunction = this._activeRenderLoops[index];
  12333. renderFunction();
  12334. }
  12335. // Present
  12336. this.endFrame();
  12337. }
  12338. }
  12339. if (this._activeRenderLoops.length > 0) {
  12340. // Register new frame
  12341. var requester = null;
  12342. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12343. requester = this._vrDisplay;
  12344. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12345. }
  12346. else {
  12347. this._renderingQueueLaunched = false;
  12348. }
  12349. };
  12350. /**
  12351. * Register and execute a render loop. The engine can have more than one render function
  12352. * @param renderFunction defines the function to continuously execute
  12353. */
  12354. Engine.prototype.runRenderLoop = function (renderFunction) {
  12355. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12356. return;
  12357. }
  12358. this._activeRenderLoops.push(renderFunction);
  12359. if (!this._renderingQueueLaunched) {
  12360. this._renderingQueueLaunched = true;
  12361. this._bindedRenderFunction = this._renderLoop.bind(this);
  12362. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12363. }
  12364. };
  12365. /**
  12366. * Toggle full screen mode
  12367. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12368. * @param options defines an option object to be sent to the requestFullscreen function
  12369. */
  12370. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12371. if (this.isFullscreen) {
  12372. BABYLON.Tools.ExitFullscreen();
  12373. }
  12374. else {
  12375. this._pointerLockRequested = requestPointerLock;
  12376. if (this._renderingCanvas) {
  12377. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12378. }
  12379. }
  12380. };
  12381. /**
  12382. * Clear the current render buffer or the current render target (if any is set up)
  12383. * @param color defines the color to use
  12384. * @param backBuffer defines if the back buffer must be cleared
  12385. * @param depth defines if the depth buffer must be cleared
  12386. * @param stencil defines if the stencil buffer must be cleared
  12387. */
  12388. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12389. if (stencil === void 0) { stencil = false; }
  12390. this.applyStates();
  12391. var mode = 0;
  12392. if (backBuffer && color) {
  12393. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12394. mode |= this._gl.COLOR_BUFFER_BIT;
  12395. }
  12396. if (depth) {
  12397. this._gl.clearDepth(1.0);
  12398. mode |= this._gl.DEPTH_BUFFER_BIT;
  12399. }
  12400. if (stencil) {
  12401. this._gl.clearStencil(0);
  12402. mode |= this._gl.STENCIL_BUFFER_BIT;
  12403. }
  12404. this._gl.clear(mode);
  12405. };
  12406. /**
  12407. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12408. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12409. * @param y defines the y-coordinate of the corner of the clear rectangle
  12410. * @param width defines the width of the clear rectangle
  12411. * @param height defines the height of the clear rectangle
  12412. * @param clearColor defines the clear color
  12413. */
  12414. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12415. var gl = this._gl;
  12416. // Save state
  12417. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12418. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12419. // Change state
  12420. gl.enable(gl.SCISSOR_TEST);
  12421. gl.scissor(x, y, width, height);
  12422. // Clear
  12423. this.clear(clearColor, true, true, true);
  12424. // Restore state
  12425. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12426. if (curScissor === true) {
  12427. gl.enable(gl.SCISSOR_TEST);
  12428. }
  12429. else {
  12430. gl.disable(gl.SCISSOR_TEST);
  12431. }
  12432. };
  12433. /** @hidden */
  12434. Engine.prototype._viewport = function (x, y, width, height) {
  12435. if (x !== this._viewportCached.x ||
  12436. y !== this._viewportCached.y ||
  12437. width !== this._viewportCached.z ||
  12438. height !== this._viewportCached.w) {
  12439. this._viewportCached.x = x;
  12440. this._viewportCached.y = y;
  12441. this._viewportCached.z = width;
  12442. this._viewportCached.w = height;
  12443. this._gl.viewport(x, y, width, height);
  12444. }
  12445. };
  12446. /**
  12447. * Set the WebGL's viewport
  12448. * @param viewport defines the viewport element to be used
  12449. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12450. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12451. */
  12452. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12453. var width = requiredWidth || this.getRenderWidth();
  12454. var height = requiredHeight || this.getRenderHeight();
  12455. var x = viewport.x || 0;
  12456. var y = viewport.y || 0;
  12457. this._cachedViewport = viewport;
  12458. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12459. };
  12460. /**
  12461. * Directly set the WebGL Viewport
  12462. * @param x defines the x coordinate of the viewport (in screen space)
  12463. * @param y defines the y coordinate of the viewport (in screen space)
  12464. * @param width defines the width of the viewport (in screen space)
  12465. * @param height defines the height of the viewport (in screen space)
  12466. * @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
  12467. */
  12468. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12469. var currentViewport = this._cachedViewport;
  12470. this._cachedViewport = null;
  12471. this._viewport(x, y, width, height);
  12472. return currentViewport;
  12473. };
  12474. /**
  12475. * Begin a new frame
  12476. */
  12477. Engine.prototype.beginFrame = function () {
  12478. this.onBeginFrameObservable.notifyObservers(this);
  12479. this._measureFps();
  12480. };
  12481. /**
  12482. * Enf the current frame
  12483. */
  12484. Engine.prototype.endFrame = function () {
  12485. // Force a flush in case we are using a bad OS.
  12486. if (this._badOS) {
  12487. this.flushFramebuffer();
  12488. }
  12489. // Submit frame to the vr device, if enabled
  12490. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12491. // TODO: We should only submit the frame if we read frameData successfully.
  12492. this._vrDisplay.submitFrame();
  12493. }
  12494. this.onEndFrameObservable.notifyObservers(this);
  12495. };
  12496. /**
  12497. * Resize the view according to the canvas' size
  12498. */
  12499. Engine.prototype.resize = function () {
  12500. // We're not resizing the size of the canvas while in VR mode & presenting
  12501. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12502. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12503. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12504. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12505. }
  12506. };
  12507. /**
  12508. * Force a specific size of the canvas
  12509. * @param width defines the new canvas' width
  12510. * @param height defines the new canvas' height
  12511. */
  12512. Engine.prototype.setSize = function (width, height) {
  12513. if (!this._renderingCanvas) {
  12514. return;
  12515. }
  12516. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12517. return;
  12518. }
  12519. this._renderingCanvas.width = width;
  12520. this._renderingCanvas.height = height;
  12521. for (var index = 0; index < this.scenes.length; index++) {
  12522. var scene = this.scenes[index];
  12523. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12524. var cam = scene.cameras[camIndex];
  12525. cam._currentRenderId = 0;
  12526. }
  12527. }
  12528. if (this.onResizeObservable.hasObservers) {
  12529. this.onResizeObservable.notifyObservers(this);
  12530. }
  12531. };
  12532. // WebVR functions
  12533. /**
  12534. * Gets a boolean indicating if a webVR device was detected
  12535. * @returns true if a webVR device was detected
  12536. */
  12537. Engine.prototype.isVRDevicePresent = function () {
  12538. return !!this._vrDisplay;
  12539. };
  12540. /**
  12541. * Gets the current webVR device
  12542. * @returns the current webVR device (or null)
  12543. */
  12544. Engine.prototype.getVRDevice = function () {
  12545. return this._vrDisplay;
  12546. };
  12547. /**
  12548. * Initializes a webVR display and starts listening to display change events
  12549. * The onVRDisplayChangedObservable will be notified upon these changes
  12550. * @returns The onVRDisplayChangedObservable
  12551. */
  12552. Engine.prototype.initWebVR = function () {
  12553. this.initWebVRAsync();
  12554. return this.onVRDisplayChangedObservable;
  12555. };
  12556. /**
  12557. * Initializes a webVR display and starts listening to display change events
  12558. * The onVRDisplayChangedObservable will be notified upon these changes
  12559. * @returns A promise containing a VRDisplay and if vr is supported
  12560. */
  12561. Engine.prototype.initWebVRAsync = function () {
  12562. var _this = this;
  12563. var notifyObservers = function () {
  12564. var eventArgs = {
  12565. vrDisplay: _this._vrDisplay,
  12566. vrSupported: _this._vrSupported
  12567. };
  12568. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12569. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12570. };
  12571. if (!this._onVrDisplayConnect) {
  12572. this._onVrDisplayConnect = function (event) {
  12573. _this._vrDisplay = event.display;
  12574. notifyObservers();
  12575. };
  12576. this._onVrDisplayDisconnect = function () {
  12577. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12578. _this._vrDisplay = undefined;
  12579. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12580. notifyObservers();
  12581. };
  12582. this._onVrDisplayPresentChange = function () {
  12583. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12584. };
  12585. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12586. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12587. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12588. }
  12589. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12590. this._webVRInitPromise.then(notifyObservers);
  12591. return this._webVRInitPromise;
  12592. };
  12593. /**
  12594. * Call this function to switch to webVR mode
  12595. * Will do nothing if webVR is not supported or if there is no webVR device
  12596. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12597. */
  12598. Engine.prototype.enableVR = function () {
  12599. var _this = this;
  12600. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12601. var onResolved = function () {
  12602. _this.onVRRequestPresentComplete.notifyObservers(true);
  12603. _this._onVRFullScreenTriggered();
  12604. };
  12605. var onRejected = function () {
  12606. _this.onVRRequestPresentComplete.notifyObservers(false);
  12607. };
  12608. this.onVRRequestPresentStart.notifyObservers(this);
  12609. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12610. }
  12611. };
  12612. /**
  12613. * Call this function to leave webVR mode
  12614. * Will do nothing if webVR is not supported or if there is no webVR device
  12615. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12616. */
  12617. Engine.prototype.disableVR = function () {
  12618. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12619. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12620. }
  12621. };
  12622. Engine.prototype._getVRDisplaysAsync = function () {
  12623. var _this = this;
  12624. return new Promise(function (res, rej) {
  12625. if (navigator.getVRDisplays) {
  12626. navigator.getVRDisplays().then(function (devices) {
  12627. _this._vrSupported = true;
  12628. // note that devices may actually be an empty array. This is fine;
  12629. // we expect this._vrDisplay to be undefined in this case.
  12630. _this._vrDisplay = devices[0];
  12631. res({
  12632. vrDisplay: _this._vrDisplay,
  12633. vrSupported: _this._vrSupported
  12634. });
  12635. });
  12636. }
  12637. else {
  12638. _this._vrDisplay = undefined;
  12639. _this._vrSupported = false;
  12640. res({
  12641. vrDisplay: _this._vrDisplay,
  12642. vrSupported: _this._vrSupported
  12643. });
  12644. }
  12645. });
  12646. };
  12647. /**
  12648. * Binds the frame buffer to the specified texture.
  12649. * @param texture The texture to render to or null for the default canvas
  12650. * @param faceIndex The face of the texture to render to in case of cube texture
  12651. * @param requiredWidth The width of the target to render to
  12652. * @param requiredHeight The height of the target to render to
  12653. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12654. * @param depthStencilTexture The depth stencil texture to use to render
  12655. * @param lodLevel defines le lod level to bind to the frame buffer
  12656. */
  12657. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12658. if (lodLevel === void 0) { lodLevel = 0; }
  12659. if (this._currentRenderTarget) {
  12660. this.unBindFramebuffer(this._currentRenderTarget);
  12661. }
  12662. this._currentRenderTarget = texture;
  12663. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12664. var gl = this._gl;
  12665. if (texture.isCube) {
  12666. if (faceIndex === undefined) {
  12667. faceIndex = 0;
  12668. }
  12669. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12670. if (depthStencilTexture) {
  12671. if (depthStencilTexture._generateStencilBuffer) {
  12672. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12673. }
  12674. else {
  12675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12676. }
  12677. }
  12678. }
  12679. if (this._cachedViewport && !forceFullscreenViewport) {
  12680. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12681. }
  12682. else {
  12683. if (!requiredWidth) {
  12684. requiredWidth = texture.width;
  12685. if (lodLevel) {
  12686. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12687. }
  12688. }
  12689. if (!requiredHeight) {
  12690. requiredHeight = texture.height;
  12691. if (lodLevel) {
  12692. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12693. }
  12694. }
  12695. this._viewport(0, 0, requiredWidth, requiredHeight);
  12696. }
  12697. this.wipeCaches();
  12698. };
  12699. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12700. if (this._currentFramebuffer !== framebuffer) {
  12701. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12702. this._currentFramebuffer = framebuffer;
  12703. }
  12704. };
  12705. /**
  12706. * Unbind the current render target texture from the webGL context
  12707. * @param texture defines the render target texture to unbind
  12708. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12709. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12710. */
  12711. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12712. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12713. this._currentRenderTarget = null;
  12714. // If MSAA, we need to bitblt back to main texture
  12715. var gl = this._gl;
  12716. if (texture._MSAAFramebuffer) {
  12717. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12718. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12719. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12720. }
  12721. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12722. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12723. gl.generateMipmap(gl.TEXTURE_2D);
  12724. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12725. }
  12726. if (onBeforeUnbind) {
  12727. if (texture._MSAAFramebuffer) {
  12728. // Bind the correct framebuffer
  12729. this.bindUnboundFramebuffer(texture._framebuffer);
  12730. }
  12731. onBeforeUnbind();
  12732. }
  12733. this.bindUnboundFramebuffer(null);
  12734. };
  12735. /**
  12736. * Unbind a list of render target textures from the webGL context
  12737. * This is used only when drawBuffer extension or webGL2 are active
  12738. * @param textures defines the render target textures to unbind
  12739. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12740. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12741. */
  12742. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12743. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12744. this._currentRenderTarget = null;
  12745. // If MSAA, we need to bitblt back to main texture
  12746. var gl = this._gl;
  12747. if (textures[0]._MSAAFramebuffer) {
  12748. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12749. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12750. var attachments = textures[0]._attachments;
  12751. if (!attachments) {
  12752. attachments = new Array(textures.length);
  12753. textures[0]._attachments = attachments;
  12754. }
  12755. for (var i = 0; i < textures.length; i++) {
  12756. var texture = textures[i];
  12757. for (var j = 0; j < attachments.length; j++) {
  12758. attachments[j] = gl.NONE;
  12759. }
  12760. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12761. gl.readBuffer(attachments[i]);
  12762. gl.drawBuffers(attachments);
  12763. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12764. }
  12765. for (var i = 0; i < attachments.length; i++) {
  12766. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12767. }
  12768. gl.drawBuffers(attachments);
  12769. }
  12770. for (var i = 0; i < textures.length; i++) {
  12771. var texture = textures[i];
  12772. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12773. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12774. gl.generateMipmap(gl.TEXTURE_2D);
  12775. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12776. }
  12777. }
  12778. if (onBeforeUnbind) {
  12779. if (textures[0]._MSAAFramebuffer) {
  12780. // Bind the correct framebuffer
  12781. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12782. }
  12783. onBeforeUnbind();
  12784. }
  12785. this.bindUnboundFramebuffer(null);
  12786. };
  12787. /**
  12788. * Force the mipmap generation for the given render target texture
  12789. * @param texture defines the render target texture to use
  12790. */
  12791. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12792. if (texture.generateMipMaps) {
  12793. var gl = this._gl;
  12794. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12795. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12796. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12797. }
  12798. };
  12799. /**
  12800. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12801. */
  12802. Engine.prototype.flushFramebuffer = function () {
  12803. this._gl.flush();
  12804. };
  12805. /**
  12806. * Unbind the current render target and bind the default framebuffer
  12807. */
  12808. Engine.prototype.restoreDefaultFramebuffer = function () {
  12809. if (this._currentRenderTarget) {
  12810. this.unBindFramebuffer(this._currentRenderTarget);
  12811. }
  12812. else {
  12813. this.bindUnboundFramebuffer(null);
  12814. }
  12815. if (this._cachedViewport) {
  12816. this.setViewport(this._cachedViewport);
  12817. }
  12818. this.wipeCaches();
  12819. };
  12820. // UBOs
  12821. /**
  12822. * Create an uniform buffer
  12823. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12824. * @param elements defines the content of the uniform buffer
  12825. * @returns the webGL uniform buffer
  12826. */
  12827. Engine.prototype.createUniformBuffer = function (elements) {
  12828. var ubo = this._gl.createBuffer();
  12829. if (!ubo) {
  12830. throw new Error("Unable to create uniform buffer");
  12831. }
  12832. this.bindUniformBuffer(ubo);
  12833. if (elements instanceof Float32Array) {
  12834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12835. }
  12836. else {
  12837. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12838. }
  12839. this.bindUniformBuffer(null);
  12840. ubo.references = 1;
  12841. return ubo;
  12842. };
  12843. /**
  12844. * Create a dynamic uniform buffer
  12845. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12846. * @param elements defines the content of the uniform buffer
  12847. * @returns the webGL uniform buffer
  12848. */
  12849. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12850. var ubo = this._gl.createBuffer();
  12851. if (!ubo) {
  12852. throw new Error("Unable to create dynamic uniform buffer");
  12853. }
  12854. this.bindUniformBuffer(ubo);
  12855. if (elements instanceof Float32Array) {
  12856. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12857. }
  12858. else {
  12859. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12860. }
  12861. this.bindUniformBuffer(null);
  12862. ubo.references = 1;
  12863. return ubo;
  12864. };
  12865. /**
  12866. * Update an existing uniform buffer
  12867. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12868. * @param uniformBuffer defines the target uniform buffer
  12869. * @param elements defines the content to update
  12870. * @param offset defines the offset in the uniform buffer where update should start
  12871. * @param count defines the size of the data to update
  12872. */
  12873. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12874. this.bindUniformBuffer(uniformBuffer);
  12875. if (offset === undefined) {
  12876. offset = 0;
  12877. }
  12878. if (count === undefined) {
  12879. if (elements instanceof Float32Array) {
  12880. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12881. }
  12882. else {
  12883. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12884. }
  12885. }
  12886. else {
  12887. if (elements instanceof Float32Array) {
  12888. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12889. }
  12890. else {
  12891. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12892. }
  12893. }
  12894. this.bindUniformBuffer(null);
  12895. };
  12896. // VBOs
  12897. Engine.prototype._resetVertexBufferBinding = function () {
  12898. this.bindArrayBuffer(null);
  12899. this._cachedVertexBuffers = null;
  12900. };
  12901. /**
  12902. * Creates a vertex buffer
  12903. * @param data the data for the vertex buffer
  12904. * @returns the new WebGL static buffer
  12905. */
  12906. Engine.prototype.createVertexBuffer = function (data) {
  12907. var vbo = this._gl.createBuffer();
  12908. if (!vbo) {
  12909. throw new Error("Unable to create vertex buffer");
  12910. }
  12911. this.bindArrayBuffer(vbo);
  12912. if (data instanceof Array) {
  12913. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12914. }
  12915. else {
  12916. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12917. }
  12918. this._resetVertexBufferBinding();
  12919. vbo.references = 1;
  12920. return vbo;
  12921. };
  12922. /**
  12923. * Creates a dynamic vertex buffer
  12924. * @param data the data for the dynamic vertex buffer
  12925. * @returns the new WebGL dynamic buffer
  12926. */
  12927. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12928. var vbo = this._gl.createBuffer();
  12929. if (!vbo) {
  12930. throw new Error("Unable to create dynamic vertex buffer");
  12931. }
  12932. this.bindArrayBuffer(vbo);
  12933. if (data instanceof Array) {
  12934. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12935. }
  12936. else {
  12937. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12938. }
  12939. this._resetVertexBufferBinding();
  12940. vbo.references = 1;
  12941. return vbo;
  12942. };
  12943. /**
  12944. * Update a dynamic index buffer
  12945. * @param indexBuffer defines the target index buffer
  12946. * @param indices defines the data to update
  12947. * @param offset defines the offset in the target index buffer where update should start
  12948. */
  12949. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12950. if (offset === void 0) { offset = 0; }
  12951. // Force cache update
  12952. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12953. this.bindIndexBuffer(indexBuffer);
  12954. var arrayBuffer;
  12955. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12956. arrayBuffer = indices;
  12957. }
  12958. else {
  12959. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12960. }
  12961. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12962. this._resetIndexBufferBinding();
  12963. };
  12964. /**
  12965. * Updates a dynamic vertex buffer.
  12966. * @param vertexBuffer the vertex buffer to update
  12967. * @param data the data used to update the vertex buffer
  12968. * @param byteOffset the byte offset of the data
  12969. * @param byteLength the byte length of the data
  12970. */
  12971. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12972. this.bindArrayBuffer(vertexBuffer);
  12973. if (byteOffset === undefined) {
  12974. byteOffset = 0;
  12975. }
  12976. if (byteLength === undefined) {
  12977. if (data instanceof Array) {
  12978. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12979. }
  12980. else {
  12981. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12982. }
  12983. }
  12984. else {
  12985. if (data instanceof Array) {
  12986. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12987. }
  12988. else {
  12989. if (data instanceof ArrayBuffer) {
  12990. data = new Uint8Array(data, byteOffset, byteLength);
  12991. }
  12992. else {
  12993. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12994. }
  12995. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12996. }
  12997. }
  12998. this._resetVertexBufferBinding();
  12999. };
  13000. Engine.prototype._resetIndexBufferBinding = function () {
  13001. this.bindIndexBuffer(null);
  13002. this._cachedIndexBuffer = null;
  13003. };
  13004. /**
  13005. * Creates a new index buffer
  13006. * @param indices defines the content of the index buffer
  13007. * @param updatable defines if the index buffer must be updatable
  13008. * @returns a new webGL buffer
  13009. */
  13010. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13011. var vbo = this._gl.createBuffer();
  13012. if (!vbo) {
  13013. throw new Error("Unable to create index buffer");
  13014. }
  13015. this.bindIndexBuffer(vbo);
  13016. // Check for 32 bits indices
  13017. var arrayBuffer;
  13018. var need32Bits = false;
  13019. if (indices instanceof Uint16Array) {
  13020. arrayBuffer = indices;
  13021. }
  13022. else {
  13023. //check 32 bit support
  13024. if (this._caps.uintIndices) {
  13025. if (indices instanceof Uint32Array) {
  13026. arrayBuffer = indices;
  13027. need32Bits = true;
  13028. }
  13029. else {
  13030. //number[] or Int32Array, check if 32 bit is necessary
  13031. for (var index = 0; index < indices.length; index++) {
  13032. if (indices[index] > 65535) {
  13033. need32Bits = true;
  13034. break;
  13035. }
  13036. }
  13037. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13038. }
  13039. }
  13040. else {
  13041. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13042. arrayBuffer = new Uint16Array(indices);
  13043. }
  13044. }
  13045. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13046. this._resetIndexBufferBinding();
  13047. vbo.references = 1;
  13048. vbo.is32Bits = need32Bits;
  13049. return vbo;
  13050. };
  13051. /**
  13052. * Bind a webGL buffer to the webGL context
  13053. * @param buffer defines the buffer to bind
  13054. */
  13055. Engine.prototype.bindArrayBuffer = function (buffer) {
  13056. if (!this._vaoRecordInProgress) {
  13057. this._unbindVertexArrayObject();
  13058. }
  13059. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13060. };
  13061. /**
  13062. * Bind an uniform buffer to the current webGL context
  13063. * @param buffer defines the buffer to bind
  13064. */
  13065. Engine.prototype.bindUniformBuffer = function (buffer) {
  13066. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13067. };
  13068. /**
  13069. * Bind a buffer to the current webGL context at a given location
  13070. * @param buffer defines the buffer to bind
  13071. * @param location defines the index where to bind the buffer
  13072. */
  13073. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13074. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13075. };
  13076. /**
  13077. * Bind a specific block at a given index in a specific shader program
  13078. * @param shaderProgram defines the shader program
  13079. * @param blockName defines the block name
  13080. * @param index defines the index where to bind the block
  13081. */
  13082. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13083. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13084. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13085. };
  13086. ;
  13087. Engine.prototype.bindIndexBuffer = function (buffer) {
  13088. if (!this._vaoRecordInProgress) {
  13089. this._unbindVertexArrayObject();
  13090. }
  13091. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13092. };
  13093. Engine.prototype.bindBuffer = function (buffer, target) {
  13094. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13095. this._gl.bindBuffer(target, buffer);
  13096. this._currentBoundBuffer[target] = buffer;
  13097. }
  13098. };
  13099. /**
  13100. * update the bound buffer with the given data
  13101. * @param data defines the data to update
  13102. */
  13103. Engine.prototype.updateArrayBuffer = function (data) {
  13104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13105. };
  13106. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13107. var pointer = this._currentBufferPointers[indx];
  13108. var changed = false;
  13109. if (!pointer.active) {
  13110. changed = true;
  13111. pointer.active = true;
  13112. pointer.index = indx;
  13113. pointer.size = size;
  13114. pointer.type = type;
  13115. pointer.normalized = normalized;
  13116. pointer.stride = stride;
  13117. pointer.offset = offset;
  13118. pointer.buffer = buffer;
  13119. }
  13120. else {
  13121. if (pointer.buffer !== buffer) {
  13122. pointer.buffer = buffer;
  13123. changed = true;
  13124. }
  13125. if (pointer.size !== size) {
  13126. pointer.size = size;
  13127. changed = true;
  13128. }
  13129. if (pointer.type !== type) {
  13130. pointer.type = type;
  13131. changed = true;
  13132. }
  13133. if (pointer.normalized !== normalized) {
  13134. pointer.normalized = normalized;
  13135. changed = true;
  13136. }
  13137. if (pointer.stride !== stride) {
  13138. pointer.stride = stride;
  13139. changed = true;
  13140. }
  13141. if (pointer.offset !== offset) {
  13142. pointer.offset = offset;
  13143. changed = true;
  13144. }
  13145. }
  13146. if (changed || this._vaoRecordInProgress) {
  13147. this.bindArrayBuffer(buffer);
  13148. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13149. }
  13150. };
  13151. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13152. if (indexBuffer == null) {
  13153. return;
  13154. }
  13155. if (this._cachedIndexBuffer !== indexBuffer) {
  13156. this._cachedIndexBuffer = indexBuffer;
  13157. this.bindIndexBuffer(indexBuffer);
  13158. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13159. }
  13160. };
  13161. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13162. var attributes = effect.getAttributesNames();
  13163. if (!this._vaoRecordInProgress) {
  13164. this._unbindVertexArrayObject();
  13165. }
  13166. this.unbindAllAttributes();
  13167. for (var index = 0; index < attributes.length; index++) {
  13168. var order = effect.getAttributeLocation(index);
  13169. if (order >= 0) {
  13170. var vertexBuffer = vertexBuffers[attributes[index]];
  13171. if (!vertexBuffer) {
  13172. continue;
  13173. }
  13174. this._gl.enableVertexAttribArray(order);
  13175. if (!this._vaoRecordInProgress) {
  13176. this._vertexAttribArraysEnabled[order] = true;
  13177. }
  13178. var buffer = vertexBuffer.getBuffer();
  13179. if (buffer) {
  13180. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13181. if (vertexBuffer.getIsInstanced()) {
  13182. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13183. if (!this._vaoRecordInProgress) {
  13184. this._currentInstanceLocations.push(order);
  13185. this._currentInstanceBuffers.push(buffer);
  13186. }
  13187. }
  13188. }
  13189. }
  13190. }
  13191. };
  13192. /**
  13193. * Records a vertex array object
  13194. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13195. * @param vertexBuffers defines the list of vertex buffers to store
  13196. * @param indexBuffer defines the index buffer to store
  13197. * @param effect defines the effect to store
  13198. * @returns the new vertex array object
  13199. */
  13200. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13201. var vao = this._gl.createVertexArray();
  13202. this._vaoRecordInProgress = true;
  13203. this._gl.bindVertexArray(vao);
  13204. this._mustWipeVertexAttributes = true;
  13205. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13206. this.bindIndexBuffer(indexBuffer);
  13207. this._vaoRecordInProgress = false;
  13208. this._gl.bindVertexArray(null);
  13209. return vao;
  13210. };
  13211. /**
  13212. * Bind a specific vertex array object
  13213. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13214. * @param vertexArrayObject defines the vertex array object to bind
  13215. * @param indexBuffer defines the index buffer to bind
  13216. */
  13217. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13218. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13219. this._cachedVertexArrayObject = vertexArrayObject;
  13220. this._gl.bindVertexArray(vertexArrayObject);
  13221. this._cachedVertexBuffers = null;
  13222. this._cachedIndexBuffer = null;
  13223. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13224. this._mustWipeVertexAttributes = true;
  13225. }
  13226. };
  13227. /**
  13228. * Bind webGl buffers directly to the webGL context
  13229. * @param vertexBuffer defines the vertex buffer to bind
  13230. * @param indexBuffer defines the index buffer to bind
  13231. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13232. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13233. * @param effect defines the effect associated with the vertex buffer
  13234. */
  13235. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13236. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13237. this._cachedVertexBuffers = vertexBuffer;
  13238. this._cachedEffectForVertexBuffers = effect;
  13239. var attributesCount = effect.getAttributesCount();
  13240. this._unbindVertexArrayObject();
  13241. this.unbindAllAttributes();
  13242. var offset = 0;
  13243. for (var index = 0; index < attributesCount; index++) {
  13244. if (index < vertexDeclaration.length) {
  13245. var order = effect.getAttributeLocation(index);
  13246. if (order >= 0) {
  13247. this._gl.enableVertexAttribArray(order);
  13248. this._vertexAttribArraysEnabled[order] = true;
  13249. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13250. }
  13251. offset += vertexDeclaration[index] * 4;
  13252. }
  13253. }
  13254. }
  13255. this._bindIndexBufferWithCache(indexBuffer);
  13256. };
  13257. Engine.prototype._unbindVertexArrayObject = function () {
  13258. if (!this._cachedVertexArrayObject) {
  13259. return;
  13260. }
  13261. this._cachedVertexArrayObject = null;
  13262. this._gl.bindVertexArray(null);
  13263. };
  13264. /**
  13265. * Bind a list of vertex buffers to the webGL context
  13266. * @param vertexBuffers defines the list of vertex buffers to bind
  13267. * @param indexBuffer defines the index buffer to bind
  13268. * @param effect defines the effect associated with the vertex buffers
  13269. */
  13270. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13271. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13272. this._cachedVertexBuffers = vertexBuffers;
  13273. this._cachedEffectForVertexBuffers = effect;
  13274. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13275. }
  13276. this._bindIndexBufferWithCache(indexBuffer);
  13277. };
  13278. /**
  13279. * Unbind all instance attributes
  13280. */
  13281. Engine.prototype.unbindInstanceAttributes = function () {
  13282. var boundBuffer;
  13283. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13284. var instancesBuffer = this._currentInstanceBuffers[i];
  13285. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13286. boundBuffer = instancesBuffer;
  13287. this.bindArrayBuffer(instancesBuffer);
  13288. }
  13289. var offsetLocation = this._currentInstanceLocations[i];
  13290. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13291. }
  13292. this._currentInstanceBuffers.length = 0;
  13293. this._currentInstanceLocations.length = 0;
  13294. };
  13295. /**
  13296. * Release and free the memory of a vertex array object
  13297. * @param vao defines the vertex array object to delete
  13298. */
  13299. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13300. this._gl.deleteVertexArray(vao);
  13301. };
  13302. /** @hidden */
  13303. Engine.prototype._releaseBuffer = function (buffer) {
  13304. buffer.references--;
  13305. if (buffer.references === 0) {
  13306. this._gl.deleteBuffer(buffer);
  13307. return true;
  13308. }
  13309. return false;
  13310. };
  13311. /**
  13312. * Creates a webGL buffer to use with instanciation
  13313. * @param capacity defines the size of the buffer
  13314. * @returns the webGL buffer
  13315. */
  13316. Engine.prototype.createInstancesBuffer = function (capacity) {
  13317. var buffer = this._gl.createBuffer();
  13318. if (!buffer) {
  13319. throw new Error("Unable to create instance buffer");
  13320. }
  13321. buffer.capacity = capacity;
  13322. this.bindArrayBuffer(buffer);
  13323. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13324. return buffer;
  13325. };
  13326. /**
  13327. * Delete a webGL buffer used with instanciation
  13328. * @param buffer defines the webGL buffer to delete
  13329. */
  13330. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13331. this._gl.deleteBuffer(buffer);
  13332. };
  13333. /**
  13334. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13335. * @param instancesBuffer defines the webGL buffer to update and bind
  13336. * @param data defines the data to store in the buffer
  13337. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13338. */
  13339. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13340. this.bindArrayBuffer(instancesBuffer);
  13341. if (data) {
  13342. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13343. }
  13344. if (offsetLocations[0].index !== undefined) {
  13345. var stride = 0;
  13346. for (var i = 0; i < offsetLocations.length; i++) {
  13347. var ai = offsetLocations[i];
  13348. stride += ai.attributeSize * 4;
  13349. }
  13350. for (var i = 0; i < offsetLocations.length; i++) {
  13351. var ai = offsetLocations[i];
  13352. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13353. this._gl.enableVertexAttribArray(ai.index);
  13354. this._vertexAttribArraysEnabled[ai.index] = true;
  13355. }
  13356. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13357. this._gl.vertexAttribDivisor(ai.index, 1);
  13358. this._currentInstanceLocations.push(ai.index);
  13359. this._currentInstanceBuffers.push(instancesBuffer);
  13360. }
  13361. }
  13362. else {
  13363. for (var index = 0; index < 4; index++) {
  13364. var offsetLocation = offsetLocations[index];
  13365. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13366. this._gl.enableVertexAttribArray(offsetLocation);
  13367. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13368. }
  13369. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13370. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13371. this._currentInstanceLocations.push(offsetLocation);
  13372. this._currentInstanceBuffers.push(instancesBuffer);
  13373. }
  13374. }
  13375. };
  13376. /**
  13377. * Apply all cached states (depth, culling, stencil and alpha)
  13378. */
  13379. Engine.prototype.applyStates = function () {
  13380. this._depthCullingState.apply(this._gl);
  13381. this._stencilState.apply(this._gl);
  13382. this._alphaState.apply(this._gl);
  13383. };
  13384. /**
  13385. * Send a draw order
  13386. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13387. * @param indexStart defines the starting index
  13388. * @param indexCount defines the number of index to draw
  13389. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13390. */
  13391. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13392. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13393. };
  13394. /**
  13395. * Draw a list of points
  13396. * @param verticesStart defines the index of first vertex to draw
  13397. * @param verticesCount defines the count of vertices to draw
  13398. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13399. */
  13400. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13401. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13402. };
  13403. /**
  13404. * Draw a list of unindexed primitives
  13405. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13406. * @param verticesStart defines the index of first vertex to draw
  13407. * @param verticesCount defines the count of vertices to draw
  13408. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13409. */
  13410. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13411. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13412. };
  13413. /**
  13414. * Draw a list of indexed primitives
  13415. * @param fillMode defines the primitive to use
  13416. * @param indexStart defines the starting index
  13417. * @param indexCount defines the number of index to draw
  13418. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13419. */
  13420. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13421. // Apply states
  13422. this.applyStates();
  13423. this._drawCalls.addCount(1, false);
  13424. // Render
  13425. var drawMode = this._drawMode(fillMode);
  13426. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13427. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13428. if (instancesCount) {
  13429. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13430. }
  13431. else {
  13432. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13433. }
  13434. };
  13435. /**
  13436. * Draw a list of unindexed primitives
  13437. * @param fillMode defines the primitive to use
  13438. * @param verticesStart defines the index of first vertex to draw
  13439. * @param verticesCount defines the count of vertices to draw
  13440. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13441. */
  13442. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13443. // Apply states
  13444. this.applyStates();
  13445. this._drawCalls.addCount(1, false);
  13446. var drawMode = this._drawMode(fillMode);
  13447. if (instancesCount) {
  13448. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13449. }
  13450. else {
  13451. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13452. }
  13453. };
  13454. Engine.prototype._drawMode = function (fillMode) {
  13455. switch (fillMode) {
  13456. // Triangle views
  13457. case BABYLON.Material.TriangleFillMode:
  13458. return this._gl.TRIANGLES;
  13459. case BABYLON.Material.PointFillMode:
  13460. return this._gl.POINTS;
  13461. case BABYLON.Material.WireFrameFillMode:
  13462. return this._gl.LINES;
  13463. // Draw modes
  13464. case BABYLON.Material.PointListDrawMode:
  13465. return this._gl.POINTS;
  13466. case BABYLON.Material.LineListDrawMode:
  13467. return this._gl.LINES;
  13468. case BABYLON.Material.LineLoopDrawMode:
  13469. return this._gl.LINE_LOOP;
  13470. case BABYLON.Material.LineStripDrawMode:
  13471. return this._gl.LINE_STRIP;
  13472. case BABYLON.Material.TriangleStripDrawMode:
  13473. return this._gl.TRIANGLE_STRIP;
  13474. case BABYLON.Material.TriangleFanDrawMode:
  13475. return this._gl.TRIANGLE_FAN;
  13476. default:
  13477. return this._gl.TRIANGLES;
  13478. }
  13479. };
  13480. // Shaders
  13481. /** @hidden */
  13482. Engine.prototype._releaseEffect = function (effect) {
  13483. if (this._compiledEffects[effect._key]) {
  13484. delete this._compiledEffects[effect._key];
  13485. this._deleteProgram(effect.getProgram());
  13486. }
  13487. };
  13488. /** @hidden */
  13489. Engine.prototype._deleteProgram = function (program) {
  13490. if (program) {
  13491. program.__SPECTOR_rebuildProgram = null;
  13492. if (program.transformFeedback) {
  13493. this.deleteTransformFeedback(program.transformFeedback);
  13494. program.transformFeedback = null;
  13495. }
  13496. this._gl.deleteProgram(program);
  13497. }
  13498. };
  13499. /**
  13500. * Create a new effect (used to store vertex/fragment shaders)
  13501. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13502. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13503. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13504. * @param samplers defines an array of string used to represent textures
  13505. * @param defines defines the string containing the defines to use to compile the shaders
  13506. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13507. * @param onCompiled defines a function to call when the effect creation is successful
  13508. * @param onError defines a function to call when the effect creation has failed
  13509. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13510. * @returns the new Effect
  13511. */
  13512. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13513. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13514. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13515. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13516. if (this._compiledEffects[name]) {
  13517. var compiledEffect = this._compiledEffects[name];
  13518. if (onCompiled && compiledEffect.isReady()) {
  13519. onCompiled(compiledEffect);
  13520. }
  13521. return compiledEffect;
  13522. }
  13523. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13524. effect._key = name;
  13525. this._compiledEffects[name] = effect;
  13526. return effect;
  13527. };
  13528. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13529. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13530. };
  13531. ;
  13532. Engine.prototype._compileRawShader = function (source, type) {
  13533. var gl = this._gl;
  13534. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13535. gl.shaderSource(shader, source);
  13536. gl.compileShader(shader);
  13537. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13538. var log = gl.getShaderInfoLog(shader);
  13539. if (log) {
  13540. throw new Error(log);
  13541. }
  13542. }
  13543. if (!shader) {
  13544. throw new Error("Something went wrong while compile the shader.");
  13545. }
  13546. return shader;
  13547. };
  13548. ;
  13549. /**
  13550. * Directly creates a webGL program
  13551. * @param vertexCode defines the vertex shader code to use
  13552. * @param fragmentCode defines the fragment shader code to use
  13553. * @param context defines the webGL context to use (if not set, the current one will be used)
  13554. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13555. * @returns the new webGL program
  13556. */
  13557. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13558. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13559. context = context || this._gl;
  13560. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13561. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13562. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13563. };
  13564. /**
  13565. * Creates a webGL program
  13566. * @param vertexCode defines the vertex shader code to use
  13567. * @param fragmentCode defines the fragment shader code to use
  13568. * @param defines defines the string containing the defines to use to compile the shaders
  13569. * @param context defines the webGL context to use (if not set, the current one will be used)
  13570. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13571. * @returns the new webGL program
  13572. */
  13573. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13574. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13575. context = context || this._gl;
  13576. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13577. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13578. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13579. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13580. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13581. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13582. return program;
  13583. };
  13584. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13585. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13586. var shaderProgram = context.createProgram();
  13587. if (!shaderProgram) {
  13588. throw new Error("Unable to create program");
  13589. }
  13590. context.attachShader(shaderProgram, vertexShader);
  13591. context.attachShader(shaderProgram, fragmentShader);
  13592. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13593. var transformFeedback = this.createTransformFeedback();
  13594. this.bindTransformFeedback(transformFeedback);
  13595. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13596. shaderProgram.transformFeedback = transformFeedback;
  13597. }
  13598. context.linkProgram(shaderProgram);
  13599. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13600. this.bindTransformFeedback(null);
  13601. }
  13602. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13603. if (!linked) {
  13604. var error = context.getProgramInfoLog(shaderProgram);
  13605. if (error) {
  13606. throw new Error(error);
  13607. }
  13608. }
  13609. if (this.validateShaderPrograms) {
  13610. context.validateProgram(shaderProgram);
  13611. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13612. if (!validated) {
  13613. var error = context.getProgramInfoLog(shaderProgram);
  13614. if (error) {
  13615. throw new Error(error);
  13616. }
  13617. }
  13618. }
  13619. context.deleteShader(vertexShader);
  13620. context.deleteShader(fragmentShader);
  13621. return shaderProgram;
  13622. };
  13623. /**
  13624. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13625. * @param shaderProgram defines the webGL program to use
  13626. * @param uniformsNames defines the list of uniform names
  13627. * @returns an array of webGL uniform locations
  13628. */
  13629. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13630. var results = new Array();
  13631. for (var index = 0; index < uniformsNames.length; index++) {
  13632. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13633. }
  13634. return results;
  13635. };
  13636. /**
  13637. * Gets the lsit of active attributes for a given webGL program
  13638. * @param shaderProgram defines the webGL program to use
  13639. * @param attributesNames defines the list of attribute names to get
  13640. * @returns an array of indices indicating the offset of each attribute
  13641. */
  13642. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13643. var results = [];
  13644. for (var index = 0; index < attributesNames.length; index++) {
  13645. try {
  13646. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13647. }
  13648. catch (e) {
  13649. results.push(-1);
  13650. }
  13651. }
  13652. return results;
  13653. };
  13654. /**
  13655. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13656. * @param effect defines the effect to activate
  13657. */
  13658. Engine.prototype.enableEffect = function (effect) {
  13659. if (!effect) {
  13660. return;
  13661. }
  13662. // Use program
  13663. this.bindSamplers(effect);
  13664. this._currentEffect = effect;
  13665. if (effect.onBind) {
  13666. effect.onBind(effect);
  13667. }
  13668. effect.onBindObservable.notifyObservers(effect);
  13669. };
  13670. /**
  13671. * Set the value of an uniform to an array of int32
  13672. * @param uniform defines the webGL uniform location where to store the value
  13673. * @param array defines the array of int32 to store
  13674. */
  13675. Engine.prototype.setIntArray = function (uniform, array) {
  13676. if (!uniform)
  13677. return;
  13678. this._gl.uniform1iv(uniform, array);
  13679. };
  13680. /**
  13681. * Set the value of an uniform to an array of int32 (stored as vec2)
  13682. * @param uniform defines the webGL uniform location where to store the value
  13683. * @param array defines the array of int32 to store
  13684. */
  13685. Engine.prototype.setIntArray2 = function (uniform, array) {
  13686. if (!uniform || array.length % 2 !== 0)
  13687. return;
  13688. this._gl.uniform2iv(uniform, array);
  13689. };
  13690. /**
  13691. * Set the value of an uniform to an array of int32 (stored as vec3)
  13692. * @param uniform defines the webGL uniform location where to store the value
  13693. * @param array defines the array of int32 to store
  13694. */
  13695. Engine.prototype.setIntArray3 = function (uniform, array) {
  13696. if (!uniform || array.length % 3 !== 0)
  13697. return;
  13698. this._gl.uniform3iv(uniform, array);
  13699. };
  13700. /**
  13701. * Set the value of an uniform to an array of int32 (stored as vec4)
  13702. * @param uniform defines the webGL uniform location where to store the value
  13703. * @param array defines the array of int32 to store
  13704. */
  13705. Engine.prototype.setIntArray4 = function (uniform, array) {
  13706. if (!uniform || array.length % 4 !== 0)
  13707. return;
  13708. this._gl.uniform4iv(uniform, array);
  13709. };
  13710. /**
  13711. * Set the value of an uniform to an array of float32
  13712. * @param uniform defines the webGL uniform location where to store the value
  13713. * @param array defines the array of float32 to store
  13714. */
  13715. Engine.prototype.setFloatArray = function (uniform, array) {
  13716. if (!uniform)
  13717. return;
  13718. this._gl.uniform1fv(uniform, array);
  13719. };
  13720. /**
  13721. * Set the value of an uniform to an array of float32 (stored as vec2)
  13722. * @param uniform defines the webGL uniform location where to store the value
  13723. * @param array defines the array of float32 to store
  13724. */
  13725. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13726. if (!uniform || array.length % 2 !== 0)
  13727. return;
  13728. this._gl.uniform2fv(uniform, array);
  13729. };
  13730. /**
  13731. * Set the value of an uniform to an array of float32 (stored as vec3)
  13732. * @param uniform defines the webGL uniform location where to store the value
  13733. * @param array defines the array of float32 to store
  13734. */
  13735. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13736. if (!uniform || array.length % 3 !== 0)
  13737. return;
  13738. this._gl.uniform3fv(uniform, array);
  13739. };
  13740. /**
  13741. * Set the value of an uniform to an array of float32 (stored as vec4)
  13742. * @param uniform defines the webGL uniform location where to store the value
  13743. * @param array defines the array of float32 to store
  13744. */
  13745. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13746. if (!uniform || array.length % 4 !== 0)
  13747. return;
  13748. this._gl.uniform4fv(uniform, array);
  13749. };
  13750. /**
  13751. * Set the value of an uniform to an array of number
  13752. * @param uniform defines the webGL uniform location where to store the value
  13753. * @param array defines the array of number to store
  13754. */
  13755. Engine.prototype.setArray = function (uniform, array) {
  13756. if (!uniform)
  13757. return;
  13758. this._gl.uniform1fv(uniform, array);
  13759. };
  13760. /**
  13761. * Set the value of an uniform to an array of number (stored as vec2)
  13762. * @param uniform defines the webGL uniform location where to store the value
  13763. * @param array defines the array of number to store
  13764. */
  13765. Engine.prototype.setArray2 = function (uniform, array) {
  13766. if (!uniform || array.length % 2 !== 0)
  13767. return;
  13768. this._gl.uniform2fv(uniform, array);
  13769. };
  13770. /**
  13771. * Set the value of an uniform to an array of number (stored as vec3)
  13772. * @param uniform defines the webGL uniform location where to store the value
  13773. * @param array defines the array of number to store
  13774. */
  13775. Engine.prototype.setArray3 = function (uniform, array) {
  13776. if (!uniform || array.length % 3 !== 0)
  13777. return;
  13778. this._gl.uniform3fv(uniform, array);
  13779. };
  13780. /**
  13781. * Set the value of an uniform to an array of number (stored as vec4)
  13782. * @param uniform defines the webGL uniform location where to store the value
  13783. * @param array defines the array of number to store
  13784. */
  13785. Engine.prototype.setArray4 = function (uniform, array) {
  13786. if (!uniform || array.length % 4 !== 0)
  13787. return;
  13788. this._gl.uniform4fv(uniform, array);
  13789. };
  13790. /**
  13791. * Set the value of an uniform to an array of float32 (stored as matrices)
  13792. * @param uniform defines the webGL uniform location where to store the value
  13793. * @param matrices defines the array of float32 to store
  13794. */
  13795. Engine.prototype.setMatrices = function (uniform, matrices) {
  13796. if (!uniform)
  13797. return;
  13798. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13799. };
  13800. /**
  13801. * Set the value of an uniform to a matrix
  13802. * @param uniform defines the webGL uniform location where to store the value
  13803. * @param matrix defines the matrix to store
  13804. */
  13805. Engine.prototype.setMatrix = function (uniform, matrix) {
  13806. if (!uniform)
  13807. return;
  13808. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13809. };
  13810. /**
  13811. * Set the value of an uniform to a matrix (3x3)
  13812. * @param uniform defines the webGL uniform location where to store the value
  13813. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13814. */
  13815. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13816. if (!uniform)
  13817. return;
  13818. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13819. };
  13820. /**
  13821. * Set the value of an uniform to a matrix (2x2)
  13822. * @param uniform defines the webGL uniform location where to store the value
  13823. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13824. */
  13825. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13826. if (!uniform)
  13827. return;
  13828. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13829. };
  13830. /**
  13831. * Set the value of an uniform to a number (int)
  13832. * @param uniform defines the webGL uniform location where to store the value
  13833. * @param value defines the int number to store
  13834. */
  13835. Engine.prototype.setInt = function (uniform, value) {
  13836. if (!uniform)
  13837. return;
  13838. this._gl.uniform1i(uniform, value);
  13839. };
  13840. /**
  13841. * Set the value of an uniform to a number (float)
  13842. * @param uniform defines the webGL uniform location where to store the value
  13843. * @param value defines the float number to store
  13844. */
  13845. Engine.prototype.setFloat = function (uniform, value) {
  13846. if (!uniform)
  13847. return;
  13848. this._gl.uniform1f(uniform, value);
  13849. };
  13850. /**
  13851. * Set the value of an uniform to a vec2
  13852. * @param uniform defines the webGL uniform location where to store the value
  13853. * @param x defines the 1st component of the value
  13854. * @param y defines the 2nd component of the value
  13855. */
  13856. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13857. if (!uniform)
  13858. return;
  13859. this._gl.uniform2f(uniform, x, y);
  13860. };
  13861. /**
  13862. * Set the value of an uniform to a vec3
  13863. * @param uniform defines the webGL uniform location where to store the value
  13864. * @param x defines the 1st component of the value
  13865. * @param y defines the 2nd component of the value
  13866. * @param z defines the 3rd component of the value
  13867. */
  13868. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13869. if (!uniform)
  13870. return;
  13871. this._gl.uniform3f(uniform, x, y, z);
  13872. };
  13873. /**
  13874. * Set the value of an uniform to a boolean
  13875. * @param uniform defines the webGL uniform location where to store the value
  13876. * @param bool defines the boolean to store
  13877. */
  13878. Engine.prototype.setBool = function (uniform, bool) {
  13879. if (!uniform)
  13880. return;
  13881. this._gl.uniform1i(uniform, bool);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to a vec4
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param x defines the 1st component of the value
  13887. * @param y defines the 2nd component of the value
  13888. * @param z defines the 3rd component of the value
  13889. * @param w defines the 4th component of the value
  13890. */
  13891. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniform4f(uniform, x, y, z, w);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a Color3
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param color3 defines the color to store
  13900. */
  13901. Engine.prototype.setColor3 = function (uniform, color3) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a Color3 and an alpha value
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param color3 defines the color to store
  13910. * @param alpha defines the alpha component to store
  13911. */
  13912. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13913. if (!uniform)
  13914. return;
  13915. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13916. };
  13917. /**
  13918. * Sets a Color4 on a uniform variable
  13919. * @param uniform defines the uniform location
  13920. * @param color4 defines the value to be set
  13921. */
  13922. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13923. if (!uniform)
  13924. return;
  13925. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13926. };
  13927. // States
  13928. /**
  13929. * Set various states to the webGL context
  13930. * @param culling defines backface culling state
  13931. * @param zOffset defines the value to apply to zOffset (0 by default)
  13932. * @param force defines if states must be applied even if cache is up to date
  13933. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13934. */
  13935. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13936. if (zOffset === void 0) { zOffset = 0; }
  13937. if (reverseSide === void 0) { reverseSide = false; }
  13938. // Culling
  13939. if (this._depthCullingState.cull !== culling || force) {
  13940. this._depthCullingState.cull = culling;
  13941. }
  13942. // Cull face
  13943. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13944. if (this._depthCullingState.cullFace !== cullFace || force) {
  13945. this._depthCullingState.cullFace = cullFace;
  13946. }
  13947. // Z offset
  13948. this.setZOffset(zOffset);
  13949. // Front face
  13950. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13951. if (this._depthCullingState.frontFace !== frontFace || force) {
  13952. this._depthCullingState.frontFace = frontFace;
  13953. }
  13954. };
  13955. /**
  13956. * Set the z offset to apply to current rendering
  13957. * @param value defines the offset to apply
  13958. */
  13959. Engine.prototype.setZOffset = function (value) {
  13960. this._depthCullingState.zOffset = value;
  13961. };
  13962. /**
  13963. * Gets the current value of the zOffset
  13964. * @returns the current zOffset state
  13965. */
  13966. Engine.prototype.getZOffset = function () {
  13967. return this._depthCullingState.zOffset;
  13968. };
  13969. /**
  13970. * Enable or disable depth buffering
  13971. * @param enable defines the state to set
  13972. */
  13973. Engine.prototype.setDepthBuffer = function (enable) {
  13974. this._depthCullingState.depthTest = enable;
  13975. };
  13976. /**
  13977. * Gets a boolean indicating if depth writing is enabled
  13978. * @returns the current depth writing state
  13979. */
  13980. Engine.prototype.getDepthWrite = function () {
  13981. return this._depthCullingState.depthMask;
  13982. };
  13983. /**
  13984. * Enable or disable depth writing
  13985. * @param enable defines the state to set
  13986. */
  13987. Engine.prototype.setDepthWrite = function (enable) {
  13988. this._depthCullingState.depthMask = enable;
  13989. };
  13990. /**
  13991. * Enable or disable color writing
  13992. * @param enable defines the state to set
  13993. */
  13994. Engine.prototype.setColorWrite = function (enable) {
  13995. this._gl.colorMask(enable, enable, enable, enable);
  13996. this._colorWrite = enable;
  13997. };
  13998. /**
  13999. * Gets a boolean indicating if color writing is enabled
  14000. * @returns the current color writing state
  14001. */
  14002. Engine.prototype.getColorWrite = function () {
  14003. return this._colorWrite;
  14004. };
  14005. /**
  14006. * Sets alpha constants used by some alpha blending modes
  14007. * @param r defines the red component
  14008. * @param g defines the green component
  14009. * @param b defines the blue component
  14010. * @param a defines the alpha component
  14011. */
  14012. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14013. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14014. };
  14015. /**
  14016. * Sets the current alpha mode
  14017. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14018. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14019. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14020. */
  14021. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14022. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14023. if (this._alphaMode === mode) {
  14024. return;
  14025. }
  14026. switch (mode) {
  14027. case Engine.ALPHA_DISABLE:
  14028. this._alphaState.alphaBlend = false;
  14029. break;
  14030. case Engine.ALPHA_PREMULTIPLIED:
  14031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14032. this._alphaState.alphaBlend = true;
  14033. break;
  14034. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14035. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14036. this._alphaState.alphaBlend = true;
  14037. break;
  14038. case Engine.ALPHA_COMBINE:
  14039. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14040. this._alphaState.alphaBlend = true;
  14041. break;
  14042. case Engine.ALPHA_ONEONE:
  14043. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14044. this._alphaState.alphaBlend = true;
  14045. break;
  14046. case Engine.ALPHA_ADD:
  14047. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14048. this._alphaState.alphaBlend = true;
  14049. break;
  14050. case Engine.ALPHA_SUBTRACT:
  14051. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14052. this._alphaState.alphaBlend = true;
  14053. break;
  14054. case Engine.ALPHA_MULTIPLY:
  14055. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14056. this._alphaState.alphaBlend = true;
  14057. break;
  14058. case Engine.ALPHA_MAXIMIZED:
  14059. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14060. this._alphaState.alphaBlend = true;
  14061. break;
  14062. case Engine.ALPHA_INTERPOLATE:
  14063. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14064. this._alphaState.alphaBlend = true;
  14065. break;
  14066. case Engine.ALPHA_SCREENMODE:
  14067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14068. this._alphaState.alphaBlend = true;
  14069. break;
  14070. }
  14071. if (!noDepthWriteChange) {
  14072. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14073. }
  14074. this._alphaMode = mode;
  14075. };
  14076. /**
  14077. * Gets the current alpha mode
  14078. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14079. * @returns the current alpha mode
  14080. */
  14081. Engine.prototype.getAlphaMode = function () {
  14082. return this._alphaMode;
  14083. };
  14084. // Textures
  14085. /**
  14086. * Clears the list of texture accessible through engine.
  14087. * This can help preventing texture load conflict due to name collision.
  14088. */
  14089. Engine.prototype.clearInternalTexturesCache = function () {
  14090. this._internalTexturesCache = [];
  14091. };
  14092. /**
  14093. * Force the entire cache to be cleared
  14094. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14095. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14096. */
  14097. Engine.prototype.wipeCaches = function (bruteForce) {
  14098. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14099. return;
  14100. }
  14101. this._currentEffect = null;
  14102. this._unpackFlipYCached = null;
  14103. this._viewportCached.x = 0;
  14104. this._viewportCached.y = 0;
  14105. this._viewportCached.z = 0;
  14106. this._viewportCached.w = 0;
  14107. if (bruteForce) {
  14108. this.resetTextureCache();
  14109. this._currentProgram = null;
  14110. this._stencilState.reset();
  14111. this._depthCullingState.reset();
  14112. this.setDepthFunctionToLessOrEqual();
  14113. this._alphaState.reset();
  14114. }
  14115. this._resetVertexBufferBinding();
  14116. this._cachedIndexBuffer = null;
  14117. this._cachedEffectForVertexBuffers = null;
  14118. this._unbindVertexArrayObject();
  14119. this.bindIndexBuffer(null);
  14120. };
  14121. /**
  14122. * Set the compressed texture format to use, based on the formats you have, and the formats
  14123. * supported by the hardware / browser.
  14124. *
  14125. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14126. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14127. * to API arguments needed to compressed textures. This puts the burden on the container
  14128. * generator to house the arcane code for determining these for current & future formats.
  14129. *
  14130. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14131. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14132. *
  14133. * Note: The result of this call is not taken into account when a texture is base64.
  14134. *
  14135. * @param formatsAvailable defines the list of those format families you have created
  14136. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14137. *
  14138. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14139. * @returns The extension selected.
  14140. */
  14141. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14142. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14143. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14144. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14145. return this._textureFormatInUse = this._texturesSupported[i];
  14146. }
  14147. }
  14148. }
  14149. // actively set format to nothing, to allow this to be called more than once
  14150. // and possibly fail the 2nd time
  14151. this._textureFormatInUse = null;
  14152. return null;
  14153. };
  14154. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14155. var gl = this._gl;
  14156. var magFilter = gl.NEAREST;
  14157. var minFilter = gl.NEAREST;
  14158. switch (samplingMode) {
  14159. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14160. magFilter = gl.LINEAR;
  14161. if (generateMipMaps) {
  14162. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14163. }
  14164. else {
  14165. minFilter = gl.LINEAR;
  14166. }
  14167. break;
  14168. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14169. magFilter = gl.LINEAR;
  14170. if (generateMipMaps) {
  14171. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14172. }
  14173. else {
  14174. minFilter = gl.LINEAR;
  14175. }
  14176. break;
  14177. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14178. magFilter = gl.NEAREST;
  14179. if (generateMipMaps) {
  14180. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14181. }
  14182. else {
  14183. minFilter = gl.NEAREST;
  14184. }
  14185. break;
  14186. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14187. magFilter = gl.NEAREST;
  14188. if (generateMipMaps) {
  14189. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14190. }
  14191. else {
  14192. minFilter = gl.NEAREST;
  14193. }
  14194. break;
  14195. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14196. magFilter = gl.NEAREST;
  14197. if (generateMipMaps) {
  14198. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14199. }
  14200. else {
  14201. minFilter = gl.LINEAR;
  14202. }
  14203. break;
  14204. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14205. magFilter = gl.NEAREST;
  14206. if (generateMipMaps) {
  14207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14208. }
  14209. else {
  14210. minFilter = gl.LINEAR;
  14211. }
  14212. break;
  14213. case Engine.TEXTURE_NEAREST_LINEAR:
  14214. magFilter = gl.NEAREST;
  14215. minFilter = gl.LINEAR;
  14216. break;
  14217. case Engine.TEXTURE_NEAREST_NEAREST:
  14218. magFilter = gl.NEAREST;
  14219. minFilter = gl.NEAREST;
  14220. break;
  14221. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14222. magFilter = gl.LINEAR;
  14223. if (generateMipMaps) {
  14224. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14225. }
  14226. else {
  14227. minFilter = gl.NEAREST;
  14228. }
  14229. break;
  14230. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14231. magFilter = gl.LINEAR;
  14232. if (generateMipMaps) {
  14233. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14234. }
  14235. else {
  14236. minFilter = gl.NEAREST;
  14237. }
  14238. break;
  14239. case Engine.TEXTURE_LINEAR_LINEAR:
  14240. magFilter = gl.LINEAR;
  14241. minFilter = gl.LINEAR;
  14242. break;
  14243. case Engine.TEXTURE_LINEAR_NEAREST:
  14244. magFilter = gl.LINEAR;
  14245. minFilter = gl.NEAREST;
  14246. break;
  14247. }
  14248. return {
  14249. min: minFilter,
  14250. mag: magFilter
  14251. };
  14252. };
  14253. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14254. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14255. var img;
  14256. var onload = function () {
  14257. loadedImages[index] = img;
  14258. loadedImages._internalCount++;
  14259. if (scene) {
  14260. scene._removePendingData(img);
  14261. }
  14262. if (loadedImages._internalCount === 6) {
  14263. onfinish(loadedImages);
  14264. }
  14265. };
  14266. var onerror = function (message, exception) {
  14267. if (scene) {
  14268. scene._removePendingData(img);
  14269. }
  14270. if (onErrorCallBack) {
  14271. onErrorCallBack(message, exception);
  14272. }
  14273. };
  14274. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14275. if (scene) {
  14276. scene._addPendingData(img);
  14277. }
  14278. };
  14279. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14280. if (onError === void 0) { onError = null; }
  14281. var loadedImages = [];
  14282. loadedImages._internalCount = 0;
  14283. for (var index = 0; index < 6; index++) {
  14284. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14285. }
  14286. };
  14287. ;
  14288. /** @hidden */
  14289. Engine.prototype._createTexture = function () {
  14290. var texture = this._gl.createTexture();
  14291. if (!texture) {
  14292. throw new Error("Unable to create texture");
  14293. }
  14294. return texture;
  14295. };
  14296. /**
  14297. * Usually called from BABYLON.Texture.ts.
  14298. * Passed information to create a WebGLTexture
  14299. * @param urlArg defines a value which contains one of the following:
  14300. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14301. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14302. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14303. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14304. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14305. * @param scene needed for loading to the correct scene
  14306. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14307. * @param onLoad optional callback to be called upon successful completion
  14308. * @param onError optional callback to be called upon failure
  14309. * @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
  14310. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14311. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14312. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14313. */
  14314. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14315. var _this = this;
  14316. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14317. if (onLoad === void 0) { onLoad = null; }
  14318. if (onError === void 0) { onError = null; }
  14319. if (buffer === void 0) { buffer = null; }
  14320. if (fallback === void 0) { fallback = null; }
  14321. if (format === void 0) { format = null; }
  14322. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14323. var fromData = url.substr(0, 5) === "data:";
  14324. var fromBlob = url.substr(0, 5) === "blob:";
  14325. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14326. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14327. // establish the file extension, if possible
  14328. var lastDot = url.lastIndexOf('.');
  14329. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14330. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14331. var isTGA = (extension.indexOf(".tga") === 0);
  14332. // determine if a ktx file should be substituted
  14333. var isKTX = false;
  14334. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14335. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14336. isKTX = true;
  14337. }
  14338. if (scene) {
  14339. scene._addPendingData(texture);
  14340. }
  14341. texture.url = url;
  14342. texture.generateMipMaps = !noMipmap;
  14343. texture.samplingMode = samplingMode;
  14344. texture.invertY = invertY;
  14345. if (!this._doNotHandleContextLost) {
  14346. // Keep a link to the buffer only if we plan to handle context lost
  14347. texture._buffer = buffer;
  14348. }
  14349. var onLoadObserver = null;
  14350. if (onLoad && !fallback) {
  14351. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14352. }
  14353. if (!fallback)
  14354. this._internalTexturesCache.push(texture);
  14355. var onerror = function (message, exception) {
  14356. if (scene) {
  14357. scene._removePendingData(texture);
  14358. }
  14359. if (onLoadObserver && !isKTX) {
  14360. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14361. texture.onLoadedObservable.remove(onLoadObserver);
  14362. }
  14363. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14364. if (isKTX) {
  14365. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14366. }
  14367. else if (BABYLON.Tools.UseFallbackTexture) {
  14368. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14369. }
  14370. if (onError) {
  14371. onError(message || "Unknown error", exception);
  14372. }
  14373. };
  14374. var callback = null;
  14375. // processing for non-image formats
  14376. if (isKTX || isTGA || isDDS) {
  14377. if (isKTX) {
  14378. callback = function (data) {
  14379. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14380. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14381. ktx.uploadLevels(texture, !noMipmap);
  14382. return false;
  14383. }, samplingMode);
  14384. };
  14385. }
  14386. else if (isTGA) {
  14387. callback = function (arrayBuffer) {
  14388. var data = new Uint8Array(arrayBuffer);
  14389. var header = BABYLON.TGATools.GetTGAHeader(data);
  14390. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14391. BABYLON.TGATools.UploadContent(texture, data);
  14392. return false;
  14393. }, samplingMode);
  14394. };
  14395. }
  14396. else if (isDDS) {
  14397. callback = function (data) {
  14398. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14399. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14400. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14401. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 1);
  14402. return false;
  14403. }, samplingMode);
  14404. };
  14405. }
  14406. if (!buffer) {
  14407. this._loadFile(url, function (data) {
  14408. if (callback) {
  14409. callback(data);
  14410. }
  14411. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14412. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14413. });
  14414. }
  14415. else {
  14416. if (callback) {
  14417. callback(buffer);
  14418. }
  14419. }
  14420. // image format processing
  14421. }
  14422. else {
  14423. var onload = function (img) {
  14424. if (fromBlob && !_this._doNotHandleContextLost) {
  14425. // We need to store the image if we need to rebuild the texture
  14426. // in case of a webgl context lost
  14427. texture._buffer = img;
  14428. }
  14429. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14430. var gl = _this._gl;
  14431. var isPot = (img.width === potWidth && img.height === potHeight);
  14432. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14433. if (isPot) {
  14434. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14435. return false;
  14436. }
  14437. var maxTextureSize = _this._caps.maxTextureSize;
  14438. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14439. _this._prepareWorkingCanvas();
  14440. if (!_this._workingCanvas || !_this._workingContext) {
  14441. return false;
  14442. }
  14443. _this._workingCanvas.width = potWidth;
  14444. _this._workingCanvas.height = potHeight;
  14445. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14446. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14447. texture.width = potWidth;
  14448. texture.height = potHeight;
  14449. return false;
  14450. }
  14451. else {
  14452. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14453. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14454. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14455. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14460. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14461. _this._releaseTexture(source_1);
  14462. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14463. continuationCallback();
  14464. });
  14465. }
  14466. return true;
  14467. }, samplingMode);
  14468. };
  14469. if (!fromData || isBase64) {
  14470. if (buffer instanceof HTMLImageElement) {
  14471. onload(buffer);
  14472. }
  14473. else {
  14474. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14475. }
  14476. }
  14477. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14478. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14479. }
  14480. else {
  14481. onload(buffer);
  14482. }
  14483. }
  14484. return texture;
  14485. };
  14486. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14487. var _this = this;
  14488. var rtt = this.createRenderTargetTexture({
  14489. width: destination.width,
  14490. height: destination.height,
  14491. }, {
  14492. generateMipMaps: false,
  14493. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14494. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14495. generateDepthBuffer: false,
  14496. generateStencilBuffer: false
  14497. });
  14498. if (!this._rescalePostProcess) {
  14499. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14500. }
  14501. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14502. _this._rescalePostProcess.onApply = function (effect) {
  14503. effect._bindTexture("textureSampler", source);
  14504. };
  14505. var hostingScene = scene;
  14506. if (!hostingScene) {
  14507. hostingScene = _this.scenes[_this.scenes.length - 1];
  14508. }
  14509. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14510. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14511. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14512. _this.unBindFramebuffer(rtt);
  14513. _this._releaseTexture(rtt);
  14514. if (onComplete) {
  14515. onComplete();
  14516. }
  14517. });
  14518. };
  14519. /**
  14520. * Update a raw texture
  14521. * @param texture defines the texture to update
  14522. * @param data defines the data to store in the texture
  14523. * @param format defines the format of the data
  14524. * @param invertY defines if data must be stored with Y axis inverted
  14525. * @param compression defines the compression used (null by default)
  14526. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14527. */
  14528. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14529. if (compression === void 0) { compression = null; }
  14530. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14531. if (!texture) {
  14532. return;
  14533. }
  14534. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14535. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14536. // babylon's internalFormat but gl's texImage2D format
  14537. var internalFormat = this._getInternalFormat(format);
  14538. var textureType = this._getWebGLTextureType(type);
  14539. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14540. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14541. if (!this._doNotHandleContextLost) {
  14542. texture._bufferView = data;
  14543. texture.format = format;
  14544. texture.type = type;
  14545. texture.invertY = invertY;
  14546. texture._compression = compression;
  14547. }
  14548. if (texture.width % 4 !== 0) {
  14549. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14550. }
  14551. if (compression && data) {
  14552. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14553. }
  14554. else {
  14555. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14556. }
  14557. if (texture.generateMipMaps) {
  14558. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14559. }
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14561. // this.resetTextureCache();
  14562. texture.isReady = true;
  14563. };
  14564. /**
  14565. * Creates a raw texture
  14566. * @param data defines the data to store in the texture
  14567. * @param width defines the width of the texture
  14568. * @param height defines the height of the texture
  14569. * @param format defines the format of the data
  14570. * @param generateMipMaps defines if the engine should generate the mip levels
  14571. * @param invertY defines if data must be stored with Y axis inverted
  14572. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14573. * @param compression defines the compression used (null by default)
  14574. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14575. * @returns the raw texture inside an InternalTexture
  14576. */
  14577. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14578. if (compression === void 0) { compression = null; }
  14579. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14580. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14581. texture.baseWidth = width;
  14582. texture.baseHeight = height;
  14583. texture.width = width;
  14584. texture.height = height;
  14585. texture.format = format;
  14586. texture.generateMipMaps = generateMipMaps;
  14587. texture.samplingMode = samplingMode;
  14588. texture.invertY = invertY;
  14589. texture._compression = compression;
  14590. texture.type = type;
  14591. if (!this._doNotHandleContextLost) {
  14592. texture._bufferView = data;
  14593. }
  14594. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14595. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14596. // Filters
  14597. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14600. if (generateMipMaps) {
  14601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14602. }
  14603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14604. this._internalTexturesCache.push(texture);
  14605. return texture;
  14606. };
  14607. /** @hidden */
  14608. Engine.prototype._unpackFlipY = function (value) {
  14609. if (this._unpackFlipYCached !== value) {
  14610. this._unpackFlipYCached = value;
  14611. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14612. }
  14613. };
  14614. /** @hidden */
  14615. Engine.prototype._getUnpackAlignement = function () {
  14616. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14617. };
  14618. /**
  14619. * Creates a dynamic texture
  14620. * @param width defines the width of the texture
  14621. * @param height defines the height of the texture
  14622. * @param generateMipMaps defines if the engine should generate the mip levels
  14623. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14624. * @returns the dynamic texture inside an InternalTexture
  14625. */
  14626. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14627. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14628. texture.baseWidth = width;
  14629. texture.baseHeight = height;
  14630. if (generateMipMaps) {
  14631. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14632. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14633. }
  14634. // this.resetTextureCache();
  14635. texture.width = width;
  14636. texture.height = height;
  14637. texture.isReady = false;
  14638. texture.generateMipMaps = generateMipMaps;
  14639. texture.samplingMode = samplingMode;
  14640. this.updateTextureSamplingMode(samplingMode, texture);
  14641. this._internalTexturesCache.push(texture);
  14642. return texture;
  14643. };
  14644. /**
  14645. * Update the sampling mode of a given texture
  14646. * @param samplingMode defines the required sampling mode
  14647. * @param texture defines the texture to update
  14648. */
  14649. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14650. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14651. if (texture.isCube) {
  14652. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14653. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14654. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14655. }
  14656. else if (texture.is3D) {
  14657. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14658. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14659. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14660. }
  14661. else {
  14662. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14663. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14665. }
  14666. texture.samplingMode = samplingMode;
  14667. };
  14668. /**
  14669. * Update the content of a dynamic texture
  14670. * @param texture defines the texture to update
  14671. * @param canvas defines the canvas containing the source
  14672. * @param invertY defines if data must be stored with Y axis inverted
  14673. * @param premulAlpha defines if alpha is stored as premultiplied
  14674. * @param format defines the format of the data
  14675. */
  14676. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14677. if (premulAlpha === void 0) { premulAlpha = false; }
  14678. if (!texture) {
  14679. return;
  14680. }
  14681. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14682. this._unpackFlipY(invertY);
  14683. if (premulAlpha) {
  14684. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14685. }
  14686. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14687. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14688. if (texture.generateMipMaps) {
  14689. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14692. if (premulAlpha) {
  14693. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14694. }
  14695. texture.isReady = true;
  14696. };
  14697. /**
  14698. * Update a video texture
  14699. * @param texture defines the texture to update
  14700. * @param video defines the video element to use
  14701. * @param invertY defines if data must be stored with Y axis inverted
  14702. */
  14703. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14704. if (!texture || texture._isDisabled) {
  14705. return;
  14706. }
  14707. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14708. this._unpackFlipY(!invertY); // Video are upside down by default
  14709. try {
  14710. // Testing video texture support
  14711. if (this._videoTextureSupported === undefined) {
  14712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14713. if (this._gl.getError() !== 0) {
  14714. this._videoTextureSupported = false;
  14715. }
  14716. else {
  14717. this._videoTextureSupported = true;
  14718. }
  14719. }
  14720. // Copy video through the current working canvas if video texture is not supported
  14721. if (!this._videoTextureSupported) {
  14722. if (!texture._workingCanvas) {
  14723. texture._workingCanvas = document.createElement("canvas");
  14724. var context = texture._workingCanvas.getContext("2d");
  14725. if (!context) {
  14726. throw new Error("Unable to get 2d context");
  14727. }
  14728. texture._workingContext = context;
  14729. texture._workingCanvas.width = texture.width;
  14730. texture._workingCanvas.height = texture.height;
  14731. }
  14732. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14733. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14734. }
  14735. else {
  14736. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14737. }
  14738. if (texture.generateMipMaps) {
  14739. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14740. }
  14741. if (!wasPreviouslyBound) {
  14742. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14743. }
  14744. // this.resetTextureCache();
  14745. texture.isReady = true;
  14746. }
  14747. catch (ex) {
  14748. // Something unexpected
  14749. // Let's disable the texture
  14750. texture._isDisabled = true;
  14751. }
  14752. };
  14753. /**
  14754. * Updates a depth texture Comparison Mode and Function.
  14755. * If the comparison Function is equal to 0, the mode will be set to none.
  14756. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14757. * @param texture The texture to set the comparison function for
  14758. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14759. */
  14760. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14761. if (this.webGLVersion === 1) {
  14762. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14763. return;
  14764. }
  14765. var gl = this._gl;
  14766. if (texture.isCube) {
  14767. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14768. if (comparisonFunction === 0) {
  14769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14771. }
  14772. else {
  14773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14775. }
  14776. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14777. }
  14778. else {
  14779. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14780. if (comparisonFunction === 0) {
  14781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14783. }
  14784. else {
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14787. }
  14788. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14789. }
  14790. texture._comparisonFunction = comparisonFunction;
  14791. };
  14792. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14793. var width = size.width || size;
  14794. var height = size.height || size;
  14795. internalTexture.baseWidth = width;
  14796. internalTexture.baseHeight = height;
  14797. internalTexture.width = width;
  14798. internalTexture.height = height;
  14799. internalTexture.isReady = true;
  14800. internalTexture.samples = 1;
  14801. internalTexture.generateMipMaps = false;
  14802. internalTexture._generateDepthBuffer = true;
  14803. internalTexture._generateStencilBuffer = generateStencil;
  14804. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14805. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14806. internalTexture._comparisonFunction = comparisonFunction;
  14807. var gl = this._gl;
  14808. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14809. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14810. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14811. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14812. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14813. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14814. if (comparisonFunction === 0) {
  14815. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14816. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14817. }
  14818. else {
  14819. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14820. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14821. }
  14822. };
  14823. /**
  14824. * Creates a depth stencil texture.
  14825. * This is only available in WebGL 2 or with the depth texture extension available.
  14826. * @param size The size of face edge in the texture.
  14827. * @param options The options defining the texture.
  14828. * @returns The texture
  14829. */
  14830. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14831. if (options.isCube) {
  14832. var width = size.width || size;
  14833. return this._createDepthStencilCubeTexture(width, options);
  14834. }
  14835. else {
  14836. return this._createDepthStencilTexture(size, options);
  14837. }
  14838. };
  14839. /**
  14840. * Creates a depth stencil texture.
  14841. * This is only available in WebGL 2 or with the depth texture extension available.
  14842. * @param size The size of face edge in the texture.
  14843. * @param options The options defining the texture.
  14844. * @returns The texture
  14845. */
  14846. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14847. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14848. if (!this._caps.depthTextureExtension) {
  14849. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14850. return internalTexture;
  14851. }
  14852. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14853. var gl = this._gl;
  14854. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14855. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14856. if (this.webGLVersion > 1) {
  14857. if (internalOptions.generateStencil) {
  14858. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14859. }
  14860. else {
  14861. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14862. }
  14863. }
  14864. else {
  14865. if (internalOptions.generateStencil) {
  14866. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14867. }
  14868. else {
  14869. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14870. }
  14871. }
  14872. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14873. return internalTexture;
  14874. };
  14875. /**
  14876. * Creates a depth stencil cube texture.
  14877. * This is only available in WebGL 2.
  14878. * @param size The size of face edge in the cube texture.
  14879. * @param options The options defining the cube texture.
  14880. * @returns The cube texture
  14881. */
  14882. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14883. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14884. internalTexture.isCube = true;
  14885. if (this.webGLVersion === 1) {
  14886. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14887. return internalTexture;
  14888. }
  14889. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14890. var gl = this._gl;
  14891. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14892. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14893. // Create the depth/stencil buffer
  14894. for (var face = 0; face < 6; face++) {
  14895. if (internalOptions.generateStencil) {
  14896. 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);
  14897. }
  14898. else {
  14899. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14900. }
  14901. }
  14902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14903. return internalTexture;
  14904. };
  14905. /**
  14906. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14907. * @param renderTarget The render target to set the frame buffer for
  14908. */
  14909. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14910. // Create the framebuffer
  14911. var internalTexture = renderTarget.getInternalTexture();
  14912. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14913. return;
  14914. }
  14915. var gl = this._gl;
  14916. var depthStencilTexture = renderTarget.depthStencilTexture;
  14917. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14918. if (depthStencilTexture.isCube) {
  14919. if (depthStencilTexture._generateStencilBuffer) {
  14920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14921. }
  14922. else {
  14923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14924. }
  14925. }
  14926. else {
  14927. if (depthStencilTexture._generateStencilBuffer) {
  14928. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14929. }
  14930. else {
  14931. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14932. }
  14933. }
  14934. this.bindUnboundFramebuffer(null);
  14935. };
  14936. /**
  14937. * Creates a new render target texture
  14938. * @param size defines the size of the texture
  14939. * @param options defines the options used to create the texture
  14940. * @returns a new render target texture stored in an InternalTexture
  14941. */
  14942. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14943. var fullOptions = new RenderTargetCreationOptions();
  14944. if (options !== undefined && typeof options === "object") {
  14945. fullOptions.generateMipMaps = options.generateMipMaps;
  14946. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14947. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14948. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14949. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14950. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14951. }
  14952. else {
  14953. fullOptions.generateMipMaps = options;
  14954. fullOptions.generateDepthBuffer = true;
  14955. fullOptions.generateStencilBuffer = false;
  14956. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14957. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14958. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14959. }
  14960. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14961. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14962. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14963. }
  14964. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14965. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14966. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14967. }
  14968. var gl = this._gl;
  14969. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14970. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14971. var width = size.width || size;
  14972. var height = size.height || size;
  14973. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14974. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14975. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14976. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14977. }
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14982. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14983. // Create the framebuffer
  14984. var currentFrameBuffer = this._currentFramebuffer;
  14985. var framebuffer = gl.createFramebuffer();
  14986. this.bindUnboundFramebuffer(framebuffer);
  14987. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14988. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14989. if (fullOptions.generateMipMaps) {
  14990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14991. }
  14992. // Unbind
  14993. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14994. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14995. this.bindUnboundFramebuffer(currentFrameBuffer);
  14996. texture._framebuffer = framebuffer;
  14997. texture.baseWidth = width;
  14998. texture.baseHeight = height;
  14999. texture.width = width;
  15000. texture.height = height;
  15001. texture.isReady = true;
  15002. texture.samples = 1;
  15003. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15004. texture.samplingMode = fullOptions.samplingMode;
  15005. texture.type = fullOptions.type;
  15006. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15007. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15008. // this.resetTextureCache();
  15009. this._internalTexturesCache.push(texture);
  15010. return texture;
  15011. };
  15012. /**
  15013. * Create a multi render target texture
  15014. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15015. * @param size defines the size of the texture
  15016. * @param options defines the creation options
  15017. * @returns the cube texture as an InternalTexture
  15018. */
  15019. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15020. var generateMipMaps = false;
  15021. var generateDepthBuffer = true;
  15022. var generateStencilBuffer = false;
  15023. var generateDepthTexture = false;
  15024. var textureCount = 1;
  15025. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15026. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15027. var types = new Array();
  15028. var samplingModes = new Array();
  15029. if (options !== undefined) {
  15030. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15031. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15032. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15033. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15034. textureCount = options.textureCount || 1;
  15035. if (options.types) {
  15036. types = options.types;
  15037. }
  15038. if (options.samplingModes) {
  15039. samplingModes = options.samplingModes;
  15040. }
  15041. }
  15042. var gl = this._gl;
  15043. // Create the framebuffer
  15044. var framebuffer = gl.createFramebuffer();
  15045. this.bindUnboundFramebuffer(framebuffer);
  15046. var width = size.width || size;
  15047. var height = size.height || size;
  15048. var textures = [];
  15049. var attachments = [];
  15050. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15051. for (var i = 0; i < textureCount; i++) {
  15052. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15053. var type = types[i] || defaultType;
  15054. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15055. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15056. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15057. }
  15058. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15059. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15060. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15061. }
  15062. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15063. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15064. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15065. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15066. }
  15067. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15068. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15069. textures.push(texture);
  15070. attachments.push(attachment);
  15071. gl.activeTexture(gl["TEXTURE" + i]);
  15072. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15073. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15077. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15078. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15079. if (generateMipMaps) {
  15080. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15081. }
  15082. // Unbind
  15083. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15084. texture._framebuffer = framebuffer;
  15085. texture._depthStencilBuffer = depthStencilBuffer;
  15086. texture.baseWidth = width;
  15087. texture.baseHeight = height;
  15088. texture.width = width;
  15089. texture.height = height;
  15090. texture.isReady = true;
  15091. texture.samples = 1;
  15092. texture.generateMipMaps = generateMipMaps;
  15093. texture.samplingMode = samplingMode;
  15094. texture.type = type;
  15095. texture._generateDepthBuffer = generateDepthBuffer;
  15096. texture._generateStencilBuffer = generateStencilBuffer;
  15097. texture._attachments = attachments;
  15098. this._internalTexturesCache.push(texture);
  15099. }
  15100. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15101. // Depth texture
  15102. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15103. gl.activeTexture(gl.TEXTURE0);
  15104. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15109. 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);
  15110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15111. depthTexture._framebuffer = framebuffer;
  15112. depthTexture.baseWidth = width;
  15113. depthTexture.baseHeight = height;
  15114. depthTexture.width = width;
  15115. depthTexture.height = height;
  15116. depthTexture.isReady = true;
  15117. depthTexture.samples = 1;
  15118. depthTexture.generateMipMaps = generateMipMaps;
  15119. depthTexture.samplingMode = gl.NEAREST;
  15120. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15121. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15122. textures.push(depthTexture);
  15123. this._internalTexturesCache.push(depthTexture);
  15124. }
  15125. gl.drawBuffers(attachments);
  15126. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15127. this.bindUnboundFramebuffer(null);
  15128. this.resetTextureCache();
  15129. return textures;
  15130. };
  15131. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15132. if (samples === void 0) { samples = 1; }
  15133. var depthStencilBuffer = null;
  15134. var gl = this._gl;
  15135. // Create the depth/stencil buffer
  15136. if (generateStencilBuffer) {
  15137. depthStencilBuffer = gl.createRenderbuffer();
  15138. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15139. if (samples > 1) {
  15140. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15141. }
  15142. else {
  15143. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15144. }
  15145. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15146. }
  15147. else if (generateDepthBuffer) {
  15148. depthStencilBuffer = gl.createRenderbuffer();
  15149. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15150. if (samples > 1) {
  15151. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15152. }
  15153. else {
  15154. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15155. }
  15156. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15157. }
  15158. return depthStencilBuffer;
  15159. };
  15160. /**
  15161. * Updates the sample count of a render target texture
  15162. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15163. * @param texture defines the texture to update
  15164. * @param samples defines the sample count to set
  15165. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15166. */
  15167. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15168. if (this.webGLVersion < 2 || !texture) {
  15169. return 1;
  15170. }
  15171. if (texture.samples === samples) {
  15172. return samples;
  15173. }
  15174. var gl = this._gl;
  15175. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15176. // Dispose previous render buffers
  15177. if (texture._depthStencilBuffer) {
  15178. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15179. texture._depthStencilBuffer = null;
  15180. }
  15181. if (texture._MSAAFramebuffer) {
  15182. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15183. texture._MSAAFramebuffer = null;
  15184. }
  15185. if (texture._MSAARenderBuffer) {
  15186. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15187. texture._MSAARenderBuffer = null;
  15188. }
  15189. if (samples > 1) {
  15190. var framebuffer = gl.createFramebuffer();
  15191. if (!framebuffer) {
  15192. throw new Error("Unable to create multi sampled framebuffer");
  15193. }
  15194. texture._MSAAFramebuffer = framebuffer;
  15195. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15196. var colorRenderbuffer = gl.createRenderbuffer();
  15197. if (!colorRenderbuffer) {
  15198. throw new Error("Unable to create multi sampled framebuffer");
  15199. }
  15200. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15202. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15203. texture._MSAARenderBuffer = colorRenderbuffer;
  15204. }
  15205. else {
  15206. this.bindUnboundFramebuffer(texture._framebuffer);
  15207. }
  15208. texture.samples = samples;
  15209. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15210. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15211. this.bindUnboundFramebuffer(null);
  15212. return samples;
  15213. };
  15214. /**
  15215. * Update the sample count for a given multiple render target texture
  15216. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15217. * @param textures defines the textures to update
  15218. * @param samples defines the sample count to set
  15219. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15220. */
  15221. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15222. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15223. return 1;
  15224. }
  15225. if (textures[0].samples === samples) {
  15226. return samples;
  15227. }
  15228. var gl = this._gl;
  15229. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15230. // Dispose previous render buffers
  15231. if (textures[0]._depthStencilBuffer) {
  15232. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15233. textures[0]._depthStencilBuffer = null;
  15234. }
  15235. if (textures[0]._MSAAFramebuffer) {
  15236. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15237. textures[0]._MSAAFramebuffer = null;
  15238. }
  15239. for (var i = 0; i < textures.length; i++) {
  15240. if (textures[i]._MSAARenderBuffer) {
  15241. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15242. textures[i]._MSAARenderBuffer = null;
  15243. }
  15244. }
  15245. if (samples > 1) {
  15246. var framebuffer = gl.createFramebuffer();
  15247. if (!framebuffer) {
  15248. throw new Error("Unable to create multi sampled framebuffer");
  15249. }
  15250. this.bindUnboundFramebuffer(framebuffer);
  15251. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15252. var attachments = [];
  15253. for (var i = 0; i < textures.length; i++) {
  15254. var texture = textures[i];
  15255. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15256. var colorRenderbuffer = gl.createRenderbuffer();
  15257. if (!colorRenderbuffer) {
  15258. throw new Error("Unable to create multi sampled framebuffer");
  15259. }
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15261. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15262. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15263. texture._MSAAFramebuffer = framebuffer;
  15264. texture._MSAARenderBuffer = colorRenderbuffer;
  15265. texture.samples = samples;
  15266. texture._depthStencilBuffer = depthStencilBuffer;
  15267. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15268. attachments.push(attachment);
  15269. }
  15270. gl.drawBuffers(attachments);
  15271. }
  15272. else {
  15273. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15274. }
  15275. this.bindUnboundFramebuffer(null);
  15276. return samples;
  15277. };
  15278. /** @hidden */
  15279. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15280. if (faceIndex === void 0) { faceIndex = 0; }
  15281. if (lod === void 0) { lod = 0; }
  15282. var gl = this._gl;
  15283. var target = gl.TEXTURE_2D;
  15284. if (texture.isCube) {
  15285. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15286. }
  15287. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15288. };
  15289. /** @hidden */
  15290. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15291. if (faceIndex === void 0) { faceIndex = 0; }
  15292. if (lod === void 0) { lod = 0; }
  15293. var gl = this._gl;
  15294. var textureType = this._getWebGLTextureType(texture.type);
  15295. var format = this._getInternalFormat(texture.format);
  15296. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15297. this._unpackFlipY(texture.invertY);
  15298. var target = gl.TEXTURE_2D;
  15299. if (texture.isCube) {
  15300. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15301. }
  15302. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15303. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15304. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15305. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15306. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15307. };
  15308. /** @hidden */
  15309. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15310. if (faceIndex === void 0) { faceIndex = 0; }
  15311. if (lod === void 0) { lod = 0; }
  15312. var gl = this._gl;
  15313. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15314. this._bindTextureDirectly(bindTarget, texture, true);
  15315. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15316. this._bindTextureDirectly(bindTarget, null, true);
  15317. };
  15318. /** @hidden */
  15319. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15320. if (faceIndex === void 0) { faceIndex = 0; }
  15321. if (lod === void 0) { lod = 0; }
  15322. var gl = this._gl;
  15323. var textureType = this._getWebGLTextureType(texture.type);
  15324. var format = this._getInternalFormat(texture.format);
  15325. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15326. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15327. this._bindTextureDirectly(bindTarget, texture, true);
  15328. this._unpackFlipY(texture.invertY);
  15329. var target = gl.TEXTURE_2D;
  15330. if (texture.isCube) {
  15331. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15332. }
  15333. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15334. this._bindTextureDirectly(bindTarget, null, true);
  15335. };
  15336. /**
  15337. * Creates a new render target cube texture
  15338. * @param size defines the size of the texture
  15339. * @param options defines the options used to create the texture
  15340. * @returns a new render target cube texture stored in an InternalTexture
  15341. */
  15342. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15343. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15344. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15345. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15346. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15347. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15348. }
  15349. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15350. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15351. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15352. }
  15353. var gl = this._gl;
  15354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15355. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15356. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15357. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15358. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15359. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15360. }
  15361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15364. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15365. for (var face = 0; face < 6; face++) {
  15366. 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);
  15367. }
  15368. // Create the framebuffer
  15369. var framebuffer = gl.createFramebuffer();
  15370. this.bindUnboundFramebuffer(framebuffer);
  15371. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15372. // MipMaps
  15373. if (fullOptions.generateMipMaps) {
  15374. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15375. }
  15376. // Unbind
  15377. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15379. this.bindUnboundFramebuffer(null);
  15380. texture._framebuffer = framebuffer;
  15381. texture.width = size;
  15382. texture.height = size;
  15383. texture.isReady = true;
  15384. texture.isCube = true;
  15385. texture.samples = 1;
  15386. texture.generateMipMaps = fullOptions.generateMipMaps;
  15387. texture.samplingMode = fullOptions.samplingMode;
  15388. texture.type = fullOptions.type;
  15389. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15390. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15391. this._internalTexturesCache.push(texture);
  15392. return texture;
  15393. };
  15394. /**
  15395. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15396. * @param rootUrl defines the url where the file to load is located
  15397. * @param scene defines the current scene
  15398. * @param lodScale defines scale to apply to the mip map selection
  15399. * @param lodOffset defines offset to apply to the mip map selection
  15400. * @param onLoad defines an optional callback raised when the texture is loaded
  15401. * @param onError defines an optional callback raised if there is an issue to load the texture
  15402. * @param format defines the format of the data
  15403. * @param forcedExtension defines the extension to use to pick the right loader
  15404. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15405. * @returns the cube texture as an InternalTexture
  15406. */
  15407. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15408. var _this = this;
  15409. if (onLoad === void 0) { onLoad = null; }
  15410. if (onError === void 0) { onError = null; }
  15411. if (forcedExtension === void 0) { forcedExtension = null; }
  15412. if (createPolynomials === void 0) { createPolynomials = true; }
  15413. var callback = function (loadData) {
  15414. if (!loadData) {
  15415. if (onLoad) {
  15416. onLoad(null);
  15417. }
  15418. return;
  15419. }
  15420. var texture = loadData.texture;
  15421. if (!createPolynomials) {
  15422. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15423. }
  15424. else if (loadData.info.sphericalPolynomial) {
  15425. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15426. }
  15427. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15428. if (_this._caps.textureLOD) {
  15429. // Do not add extra process if texture lod is supported.
  15430. if (onLoad) {
  15431. onLoad(texture);
  15432. }
  15433. return;
  15434. }
  15435. var mipSlices = 3;
  15436. var gl = _this._gl;
  15437. var width = loadData.width;
  15438. if (!width) {
  15439. return;
  15440. }
  15441. var textures = [];
  15442. for (var i = 0; i < mipSlices; i++) {
  15443. //compute LOD from even spacing in smoothness (matching shader calculation)
  15444. var smoothness = i / (mipSlices - 1);
  15445. var roughness = 1 - smoothness;
  15446. var minLODIndex = lodOffset; // roughness = 0
  15447. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15448. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15449. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15450. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15451. glTextureFromLod.isCube = true;
  15452. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15454. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15457. if (loadData.isDDS) {
  15458. var info = loadData.info;
  15459. var data = loadData.data;
  15460. _this._unpackFlipY(info.isCompressed);
  15461. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, true, 6, mipmapIndex);
  15462. }
  15463. else {
  15464. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15465. }
  15466. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15467. // Wrap in a base texture for easy binding.
  15468. var lodTexture = new BABYLON.BaseTexture(scene);
  15469. lodTexture.isCube = true;
  15470. lodTexture._texture = glTextureFromLod;
  15471. glTextureFromLod.isReady = true;
  15472. textures.push(lodTexture);
  15473. }
  15474. texture._lodTextureHigh = textures[2];
  15475. texture._lodTextureMid = textures[1];
  15476. texture._lodTextureLow = textures[0];
  15477. if (onLoad) {
  15478. onLoad(texture);
  15479. }
  15480. };
  15481. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15482. };
  15483. /**
  15484. * Creates a cube texture
  15485. * @param rootUrl defines the url where the files to load is located
  15486. * @param scene defines the current scene
  15487. * @param files defines the list of files to load (1 per face)
  15488. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15489. * @param onLoad defines an optional callback raised when the texture is loaded
  15490. * @param onError defines an optional callback raised if there is an issue to load the texture
  15491. * @param format defines the format of the data
  15492. * @param forcedExtension defines the extension to use to pick the right loader
  15493. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15494. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15495. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15496. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15497. * @returns the cube texture as an InternalTexture
  15498. */
  15499. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15500. var _this = this;
  15501. if (onLoad === void 0) { onLoad = null; }
  15502. if (onError === void 0) { onError = null; }
  15503. if (forcedExtension === void 0) { forcedExtension = null; }
  15504. if (createPolynomials === void 0) { createPolynomials = false; }
  15505. if (lodScale === void 0) { lodScale = 0; }
  15506. if (lodOffset === void 0) { lodOffset = 0; }
  15507. if (fallback === void 0) { fallback = null; }
  15508. var gl = this._gl;
  15509. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15510. texture.isCube = true;
  15511. texture.url = rootUrl;
  15512. texture.generateMipMaps = !noMipmap;
  15513. texture._lodGenerationScale = lodScale;
  15514. texture._lodGenerationOffset = lodOffset;
  15515. if (!this._doNotHandleContextLost) {
  15516. texture._extension = forcedExtension;
  15517. texture._files = files;
  15518. }
  15519. var isKTX = false;
  15520. var isDDS = false;
  15521. var isEnv = false;
  15522. var lastDot = rootUrl.lastIndexOf('.');
  15523. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15524. if (this._textureFormatInUse && !fallback) {
  15525. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15526. isKTX = true;
  15527. }
  15528. else {
  15529. isDDS = (extension === ".dds");
  15530. isEnv = (extension === ".env");
  15531. }
  15532. var onerror = function (request, exception) {
  15533. if (isKTX) {
  15534. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15535. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15536. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15537. }
  15538. if (onError && request) {
  15539. onError(request.status + " " + request.statusText, exception);
  15540. }
  15541. };
  15542. if (isKTX) {
  15543. this._loadFile(rootUrl, function (data) {
  15544. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15545. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15546. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15547. _this._unpackFlipY(true);
  15548. ktx.uploadLevels(texture, !noMipmap);
  15549. _this.setCubeMapTextureParams(gl, loadMipmap);
  15550. texture.width = ktx.pixelWidth;
  15551. texture.height = ktx.pixelHeight;
  15552. texture.isReady = true;
  15553. }, undefined, undefined, true, onerror);
  15554. }
  15555. else if (isEnv) {
  15556. this._loadFile(rootUrl, function (data) {
  15557. data = data;
  15558. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15559. if (info) {
  15560. texture.width = info.width;
  15561. texture.height = info.width;
  15562. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15563. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15564. texture.isReady = true;
  15565. if (onLoad) {
  15566. onLoad();
  15567. }
  15568. });
  15569. }
  15570. else if (onError) {
  15571. onError("Can not parse the environment file", null);
  15572. }
  15573. }, undefined, undefined, true, onerror);
  15574. }
  15575. else if (isDDS) {
  15576. if (files && files.length === 6) {
  15577. this._cascadeLoadFiles(scene, function (imgs) {
  15578. var info;
  15579. var loadMipmap = false;
  15580. var width = 0;
  15581. for (var index = 0; index < imgs.length; index++) {
  15582. var data = imgs[index];
  15583. info = BABYLON.DDSTools.GetDDSInfo(data);
  15584. texture.width = info.width;
  15585. texture.height = info.height;
  15586. width = info.width;
  15587. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15588. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15589. _this._unpackFlipY(info.isCompressed);
  15590. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6, -1, index);
  15591. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15592. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15593. }
  15594. }
  15595. _this.setCubeMapTextureParams(gl, loadMipmap);
  15596. texture.isReady = true;
  15597. if (onLoad) {
  15598. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15599. }
  15600. }, files, onError);
  15601. }
  15602. else {
  15603. this._loadFile(rootUrl, function (data) {
  15604. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15605. texture.width = info.width;
  15606. texture.height = info.height;
  15607. if (createPolynomials) {
  15608. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15609. }
  15610. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15612. _this._unpackFlipY(info.isCompressed);
  15613. BABYLON.DDSTools.UploadDDSLevels(_this, texture, data, info, loadMipmap, 6);
  15614. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15615. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15616. }
  15617. _this.setCubeMapTextureParams(gl, loadMipmap);
  15618. texture.isReady = true;
  15619. if (onLoad) {
  15620. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15621. }
  15622. }, undefined, undefined, true, onerror);
  15623. }
  15624. }
  15625. else {
  15626. if (!files) {
  15627. throw new Error("Cannot load cubemap because files were not defined");
  15628. }
  15629. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15630. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15631. var height = width;
  15632. _this._prepareWorkingCanvas();
  15633. if (!_this._workingCanvas || !_this._workingContext) {
  15634. return;
  15635. }
  15636. _this._workingCanvas.width = width;
  15637. _this._workingCanvas.height = height;
  15638. var faces = [
  15639. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15640. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15641. ];
  15642. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15643. _this._unpackFlipY(false);
  15644. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15645. for (var index = 0; index < faces.length; index++) {
  15646. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15647. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15648. }
  15649. if (!noMipmap) {
  15650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15651. }
  15652. _this.setCubeMapTextureParams(gl, !noMipmap);
  15653. texture.width = width;
  15654. texture.height = height;
  15655. texture.isReady = true;
  15656. if (format) {
  15657. texture.format = format;
  15658. }
  15659. texture.onLoadedObservable.notifyObservers(texture);
  15660. texture.onLoadedObservable.clear();
  15661. if (onLoad) {
  15662. onLoad();
  15663. }
  15664. }, files, onError);
  15665. }
  15666. this._internalTexturesCache.push(texture);
  15667. return texture;
  15668. };
  15669. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15674. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15675. // this.resetTextureCache();
  15676. };
  15677. /**
  15678. * Update a raw cube texture
  15679. * @param texture defines the texture to udpdate
  15680. * @param data defines the data to store
  15681. * @param format defines the data format
  15682. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15683. * @param invertY defines if data must be stored with Y axis inverted
  15684. * @param compression defines the compression used (null by default)
  15685. * @param level defines which level of the texture to update
  15686. */
  15687. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15688. if (compression === void 0) { compression = null; }
  15689. if (level === void 0) { level = 0; }
  15690. texture._bufferViewArray = data;
  15691. texture.format = format;
  15692. texture.type = type;
  15693. texture.invertY = invertY;
  15694. texture._compression = compression;
  15695. var gl = this._gl;
  15696. var textureType = this._getWebGLTextureType(type);
  15697. var internalFormat = this._getInternalFormat(format);
  15698. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15699. var needConversion = false;
  15700. if (internalFormat === gl.RGB) {
  15701. internalFormat = gl.RGBA;
  15702. needConversion = true;
  15703. }
  15704. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15705. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15706. if (texture.width % 4 !== 0) {
  15707. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15708. }
  15709. // Data are known to be in +X +Y +Z -X -Y -Z
  15710. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15711. var faceData = data[faceIndex];
  15712. if (compression) {
  15713. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15714. }
  15715. else {
  15716. if (needConversion) {
  15717. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15718. }
  15719. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15720. }
  15721. }
  15722. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15723. if (isPot && texture.generateMipMaps && level === 0) {
  15724. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15725. }
  15726. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15727. // this.resetTextureCache();
  15728. texture.isReady = true;
  15729. };
  15730. /**
  15731. * Creates a new raw cube texture
  15732. * @param data defines the array of data to use to create each face
  15733. * @param size defines the size of the textures
  15734. * @param format defines the format of the data
  15735. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15736. * @param generateMipMaps defines if the engine should generate the mip levels
  15737. * @param invertY defines if data must be stored with Y axis inverted
  15738. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15739. * @param compression defines the compression used (null by default)
  15740. * @returns the cube texture as an InternalTexture
  15741. */
  15742. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15743. if (compression === void 0) { compression = null; }
  15744. var gl = this._gl;
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15746. texture.isCube = true;
  15747. texture.generateMipMaps = generateMipMaps;
  15748. texture.format = format;
  15749. texture.type = type;
  15750. if (!this._doNotHandleContextLost) {
  15751. texture._bufferViewArray = data;
  15752. }
  15753. var textureType = this._getWebGLTextureType(type);
  15754. var internalFormat = this._getInternalFormat(format);
  15755. if (internalFormat === gl.RGB) {
  15756. internalFormat = gl.RGBA;
  15757. }
  15758. var width = size;
  15759. var height = width;
  15760. texture.width = width;
  15761. texture.height = height;
  15762. // Double check on POT to generate Mips.
  15763. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15764. if (!isPot) {
  15765. generateMipMaps = false;
  15766. }
  15767. // Upload data if needed. The texture won't be ready until then.
  15768. if (data) {
  15769. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15770. }
  15771. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15772. // Filters
  15773. if (data && generateMipMaps) {
  15774. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15775. }
  15776. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15779. }
  15780. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15783. }
  15784. else {
  15785. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15788. }
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15791. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15792. return texture;
  15793. };
  15794. /**
  15795. * Creates a new raw cube texture from a specified url
  15796. * @param url defines the url where the data is located
  15797. * @param scene defines the current scene
  15798. * @param size defines the size of the textures
  15799. * @param format defines the format of the data
  15800. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15801. * @param noMipmap defines if the engine should avoid generating the mip levels
  15802. * @param callback defines a callback used to extract texture data from loaded data
  15803. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15804. * @param onLoad defines a callback called when texture is loaded
  15805. * @param onError defines a callback called if there is an error
  15806. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15807. * @param invertY defines if data must be stored with Y axis inverted
  15808. * @returns the cube texture as an InternalTexture
  15809. */
  15810. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15811. var _this = this;
  15812. if (onLoad === void 0) { onLoad = null; }
  15813. if (onError === void 0) { onError = null; }
  15814. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15815. if (invertY === void 0) { invertY = false; }
  15816. var gl = this._gl;
  15817. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15818. scene._addPendingData(texture);
  15819. texture.url = url;
  15820. this._internalTexturesCache.push(texture);
  15821. var onerror = function (request, exception) {
  15822. scene._removePendingData(texture);
  15823. if (onError && request) {
  15824. onError(request.status + " " + request.statusText, exception);
  15825. }
  15826. };
  15827. var internalCallback = function (data) {
  15828. var width = texture.width;
  15829. var faceDataArrays = callback(data);
  15830. if (!faceDataArrays) {
  15831. return;
  15832. }
  15833. if (mipmapGenerator) {
  15834. var textureType = _this._getWebGLTextureType(type);
  15835. var internalFormat = _this._getInternalFormat(format);
  15836. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15837. var needConversion = false;
  15838. if (internalFormat === gl.RGB) {
  15839. internalFormat = gl.RGBA;
  15840. needConversion = true;
  15841. }
  15842. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15843. _this._unpackFlipY(false);
  15844. var mipData = mipmapGenerator(faceDataArrays);
  15845. for (var level = 0; level < mipData.length; level++) {
  15846. var mipSize = width >> level;
  15847. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15848. var mipFaceData = mipData[level][faceIndex];
  15849. if (needConversion) {
  15850. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15851. }
  15852. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15853. }
  15854. }
  15855. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15856. }
  15857. else {
  15858. texture.generateMipMaps = !noMipmap;
  15859. if (type === Engine.TEXTURETYPE_FLOAT && !_this._caps.textureFloatLinearFiltering) {
  15860. texture.generateMipMaps = false;
  15861. }
  15862. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15863. }
  15864. texture.isReady = true;
  15865. // this.resetTextureCache();
  15866. scene._removePendingData(texture);
  15867. if (onLoad) {
  15868. onLoad();
  15869. }
  15870. };
  15871. this._loadFile(url, function (data) {
  15872. internalCallback(data);
  15873. }, undefined, scene.database, true, onerror);
  15874. return texture;
  15875. };
  15876. ;
  15877. /**
  15878. * Update a raw 3D texture
  15879. * @param texture defines the texture to update
  15880. * @param data defines the data to store
  15881. * @param format defines the data format
  15882. * @param invertY defines if data must be stored with Y axis inverted
  15883. * @param compression defines the used compression (can be null)
  15884. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15885. */
  15886. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15887. if (compression === void 0) { compression = null; }
  15888. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15889. var internalType = this._getWebGLTextureType(textureType);
  15890. var internalFormat = this._getInternalFormat(format);
  15891. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15892. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15893. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15894. if (!this._doNotHandleContextLost) {
  15895. texture._bufferView = data;
  15896. texture.format = format;
  15897. texture.invertY = invertY;
  15898. texture._compression = compression;
  15899. }
  15900. if (texture.width % 4 !== 0) {
  15901. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15902. }
  15903. if (compression && data) {
  15904. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15905. }
  15906. else {
  15907. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15908. }
  15909. if (texture.generateMipMaps) {
  15910. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15911. }
  15912. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15913. // this.resetTextureCache();
  15914. texture.isReady = true;
  15915. };
  15916. /**
  15917. * Creates a new raw 3D texture
  15918. * @param data defines the data used to create the texture
  15919. * @param width defines the width of the texture
  15920. * @param height defines the height of the texture
  15921. * @param depth defines the depth of the texture
  15922. * @param format defines the format of the texture
  15923. * @param generateMipMaps defines if the engine must generate mip levels
  15924. * @param invertY defines if data must be stored with Y axis inverted
  15925. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15926. * @param compression defines the compressed used (can be null)
  15927. * @param textureType defines the compressed used (can be null)
  15928. * @returns a new raw 3D texture (stored in an InternalTexture)
  15929. */
  15930. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15931. if (compression === void 0) { compression = null; }
  15932. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15933. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15934. texture.baseWidth = width;
  15935. texture.baseHeight = height;
  15936. texture.baseDepth = depth;
  15937. texture.width = width;
  15938. texture.height = height;
  15939. texture.depth = depth;
  15940. texture.format = format;
  15941. texture.type = textureType;
  15942. texture.generateMipMaps = generateMipMaps;
  15943. texture.samplingMode = samplingMode;
  15944. texture.is3D = true;
  15945. if (!this._doNotHandleContextLost) {
  15946. texture._bufferView = data;
  15947. }
  15948. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15949. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15950. // Filters
  15951. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15952. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15953. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15954. if (generateMipMaps) {
  15955. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15956. }
  15957. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15958. this._internalTexturesCache.push(texture);
  15959. return texture;
  15960. };
  15961. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15962. var gl = this._gl;
  15963. if (!gl) {
  15964. return;
  15965. }
  15966. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15969. if (!noMipmap && !isCompressed) {
  15970. gl.generateMipmap(gl.TEXTURE_2D);
  15971. }
  15972. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15973. // this.resetTextureCache();
  15974. if (scene) {
  15975. scene._removePendingData(texture);
  15976. }
  15977. texture.onLoadedObservable.notifyObservers(texture);
  15978. texture.onLoadedObservable.clear();
  15979. };
  15980. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15981. var _this = this;
  15982. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15983. var maxTextureSize = this.getCaps().maxTextureSize;
  15984. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15985. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15986. var gl = this._gl;
  15987. if (!gl) {
  15988. return;
  15989. }
  15990. if (!texture._webGLTexture) {
  15991. // this.resetTextureCache();
  15992. if (scene) {
  15993. scene._removePendingData(texture);
  15994. }
  15995. return;
  15996. }
  15997. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15998. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15999. texture.baseWidth = width;
  16000. texture.baseHeight = height;
  16001. texture.width = potWidth;
  16002. texture.height = potHeight;
  16003. texture.isReady = true;
  16004. if (processFunction(potWidth, potHeight, function () {
  16005. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16006. })) {
  16007. // Returning as texture needs extra async steps
  16008. return;
  16009. }
  16010. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16011. };
  16012. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16013. // Create new RGBA data container.
  16014. var rgbaData;
  16015. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16016. rgbaData = new Float32Array(width * height * 4);
  16017. }
  16018. else {
  16019. rgbaData = new Uint32Array(width * height * 4);
  16020. }
  16021. // Convert each pixel.
  16022. for (var x = 0; x < width; x++) {
  16023. for (var y = 0; y < height; y++) {
  16024. var index = (y * width + x) * 3;
  16025. var newIndex = (y * width + x) * 4;
  16026. // Map Old Value to new value.
  16027. rgbaData[newIndex + 0] = rgbData[index + 0];
  16028. rgbaData[newIndex + 1] = rgbData[index + 1];
  16029. rgbaData[newIndex + 2] = rgbData[index + 2];
  16030. // Add fully opaque alpha channel.
  16031. rgbaData[newIndex + 3] = 1;
  16032. }
  16033. }
  16034. return rgbaData;
  16035. };
  16036. /** @hidden */
  16037. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16038. var gl = this._gl;
  16039. if (texture._framebuffer) {
  16040. gl.deleteFramebuffer(texture._framebuffer);
  16041. texture._framebuffer = null;
  16042. }
  16043. if (texture._depthStencilBuffer) {
  16044. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16045. texture._depthStencilBuffer = null;
  16046. }
  16047. if (texture._MSAAFramebuffer) {
  16048. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16049. texture._MSAAFramebuffer = null;
  16050. }
  16051. if (texture._MSAARenderBuffer) {
  16052. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16053. texture._MSAARenderBuffer = null;
  16054. }
  16055. };
  16056. /** @hidden */
  16057. Engine.prototype._releaseTexture = function (texture) {
  16058. var gl = this._gl;
  16059. this._releaseFramebufferObjects(texture);
  16060. gl.deleteTexture(texture._webGLTexture);
  16061. // Unbind channels
  16062. this.unbindAllTextures();
  16063. var index = this._internalTexturesCache.indexOf(texture);
  16064. if (index !== -1) {
  16065. this._internalTexturesCache.splice(index, 1);
  16066. }
  16067. // Integrated fixed lod samplers.
  16068. if (texture._lodTextureHigh) {
  16069. texture._lodTextureHigh.dispose();
  16070. }
  16071. if (texture._lodTextureMid) {
  16072. texture._lodTextureMid.dispose();
  16073. }
  16074. if (texture._lodTextureLow) {
  16075. texture._lodTextureLow.dispose();
  16076. }
  16077. // Set output texture of post process to null if the texture has been released/disposed
  16078. this.scenes.forEach(function (scene) {
  16079. scene.postProcesses.forEach(function (postProcess) {
  16080. if (postProcess._outputTexture == texture) {
  16081. postProcess._outputTexture = null;
  16082. }
  16083. });
  16084. scene.cameras.forEach(function (camera) {
  16085. camera._postProcesses.forEach(function (postProcess) {
  16086. if (postProcess) {
  16087. if (postProcess._outputTexture == texture) {
  16088. postProcess._outputTexture = null;
  16089. }
  16090. }
  16091. });
  16092. });
  16093. });
  16094. };
  16095. Engine.prototype.setProgram = function (program) {
  16096. if (this._currentProgram !== program) {
  16097. this._gl.useProgram(program);
  16098. this._currentProgram = program;
  16099. }
  16100. };
  16101. /**
  16102. * Binds an effect to the webGL context
  16103. * @param effect defines the effect to bind
  16104. */
  16105. Engine.prototype.bindSamplers = function (effect) {
  16106. this.setProgram(effect.getProgram());
  16107. var samplers = effect.getSamplers();
  16108. for (var index = 0; index < samplers.length; index++) {
  16109. var uniform = effect.getUniform(samplers[index]);
  16110. if (uniform) {
  16111. this._boundUniforms[index] = uniform;
  16112. }
  16113. }
  16114. this._currentEffect = null;
  16115. };
  16116. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16117. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16118. return;
  16119. }
  16120. // Remove
  16121. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16122. // Bind last to it
  16123. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16124. // Bind to dummy
  16125. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16126. };
  16127. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16128. if (!internalTexture) {
  16129. return -1;
  16130. }
  16131. internalTexture._initialSlot = channel;
  16132. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16133. if (channel !== internalTexture._designatedSlot) {
  16134. this._textureCollisions.addCount(1, false);
  16135. }
  16136. }
  16137. else {
  16138. if (channel !== internalTexture._designatedSlot) {
  16139. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16140. return internalTexture._designatedSlot;
  16141. }
  16142. else {
  16143. // No slot for this texture, let's pick a new one (if we find a free slot)
  16144. if (this._nextFreeTextureSlots.length) {
  16145. return this._nextFreeTextureSlots[0];
  16146. }
  16147. // We need to recycle the oldest bound texture, sorry.
  16148. this._textureCollisions.addCount(1, false);
  16149. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16150. }
  16151. }
  16152. }
  16153. return channel;
  16154. };
  16155. Engine.prototype._linkTrackers = function (previous, next) {
  16156. previous.next = next;
  16157. next.previous = previous;
  16158. };
  16159. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16160. var currentSlot = internalTexture._designatedSlot;
  16161. if (currentSlot === -1) {
  16162. return -1;
  16163. }
  16164. internalTexture._designatedSlot = -1;
  16165. if (this.disableTextureBindingOptimization) {
  16166. return -1;
  16167. }
  16168. // Remove from bound list
  16169. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16170. // Free the slot
  16171. this._boundTexturesCache[currentSlot] = null;
  16172. this._nextFreeTextureSlots.push(currentSlot);
  16173. return currentSlot;
  16174. };
  16175. Engine.prototype._activateCurrentTexture = function () {
  16176. if (this._currentTextureChannel !== this._activeChannel) {
  16177. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16178. this._currentTextureChannel = this._activeChannel;
  16179. }
  16180. };
  16181. /** @hidden */
  16182. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16183. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16184. if (force === void 0) { force = false; }
  16185. var wasPreviouslyBound = false;
  16186. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16187. this._activeChannel = texture._designatedSlot;
  16188. }
  16189. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16190. var isTextureForRendering = texture && texture._initialSlot > -1;
  16191. if (currentTextureBound !== texture || force) {
  16192. if (currentTextureBound) {
  16193. this._removeDesignatedSlot(currentTextureBound);
  16194. }
  16195. this._activateCurrentTexture();
  16196. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16197. this._boundTexturesCache[this._activeChannel] = texture;
  16198. if (texture) {
  16199. if (!this.disableTextureBindingOptimization) {
  16200. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16201. if (slotIndex > -1) {
  16202. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16203. }
  16204. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16205. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16206. }
  16207. texture._designatedSlot = this._activeChannel;
  16208. }
  16209. }
  16210. else if (forTextureDataUpdate) {
  16211. wasPreviouslyBound = true;
  16212. this._activateCurrentTexture();
  16213. }
  16214. if (isTextureForRendering && !forTextureDataUpdate) {
  16215. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16216. }
  16217. return wasPreviouslyBound;
  16218. };
  16219. /** @hidden */
  16220. Engine.prototype._bindTexture = function (channel, texture) {
  16221. if (channel < 0) {
  16222. return;
  16223. }
  16224. if (texture) {
  16225. channel = this._getCorrectTextureChannel(channel, texture);
  16226. }
  16227. this._activeChannel = channel;
  16228. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16229. };
  16230. /**
  16231. * Sets a texture to the webGL context from a postprocess
  16232. * @param channel defines the channel to use
  16233. * @param postProcess defines the source postprocess
  16234. */
  16235. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16236. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16237. };
  16238. /**
  16239. * Binds the output of the passed in post process to the texture channel specified
  16240. * @param channel The channel the texture should be bound to
  16241. * @param postProcess The post process which's output should be bound
  16242. */
  16243. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16244. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16245. };
  16246. /**
  16247. * Unbind all textures from the webGL context
  16248. */
  16249. Engine.prototype.unbindAllTextures = function () {
  16250. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16251. this._activeChannel = channel;
  16252. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16253. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16254. if (this.webGLVersion > 1) {
  16255. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16256. }
  16257. }
  16258. };
  16259. /**
  16260. * Sets a texture to the according uniform.
  16261. * @param channel The texture channel
  16262. * @param uniform The uniform to set
  16263. * @param texture The texture to apply
  16264. */
  16265. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16266. if (channel < 0) {
  16267. return;
  16268. }
  16269. if (uniform) {
  16270. this._boundUniforms[channel] = uniform;
  16271. }
  16272. this._setTexture(channel, texture);
  16273. };
  16274. /**
  16275. * Sets a depth stencil texture from a render target to the according uniform.
  16276. * @param channel The texture channel
  16277. * @param uniform The uniform to set
  16278. * @param texture The render target texture containing the depth stencil texture to apply
  16279. */
  16280. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16281. if (channel < 0) {
  16282. return;
  16283. }
  16284. if (uniform) {
  16285. this._boundUniforms[channel] = uniform;
  16286. }
  16287. if (!texture || !texture.depthStencilTexture) {
  16288. this._setTexture(channel, null);
  16289. }
  16290. else {
  16291. this._setTexture(channel, texture, false, true);
  16292. }
  16293. };
  16294. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16295. var uniform = this._boundUniforms[sourceSlot];
  16296. if (uniform._currentState === destination) {
  16297. return;
  16298. }
  16299. this._gl.uniform1i(uniform, destination);
  16300. uniform._currentState = destination;
  16301. };
  16302. Engine.prototype._getTextureWrapMode = function (mode) {
  16303. switch (mode) {
  16304. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16305. return this._gl.REPEAT;
  16306. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16307. return this._gl.CLAMP_TO_EDGE;
  16308. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16309. return this._gl.MIRRORED_REPEAT;
  16310. }
  16311. return this._gl.REPEAT;
  16312. };
  16313. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16314. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16315. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16316. // Not ready?
  16317. if (!texture) {
  16318. if (this._boundTexturesCache[channel] != null) {
  16319. this._activeChannel = channel;
  16320. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16321. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16322. if (this.webGLVersion > 1) {
  16323. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16324. }
  16325. }
  16326. return false;
  16327. }
  16328. // Video
  16329. if (texture.video) {
  16330. this._activeChannel = channel;
  16331. texture.update();
  16332. }
  16333. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16334. texture.delayLoad();
  16335. return false;
  16336. }
  16337. var internalTexture;
  16338. if (depthStencilTexture) {
  16339. internalTexture = texture.depthStencilTexture;
  16340. }
  16341. else if (texture.isReady()) {
  16342. internalTexture = texture.getInternalTexture();
  16343. }
  16344. else if (texture.isCube) {
  16345. internalTexture = this.emptyCubeTexture;
  16346. }
  16347. else if (texture.is3D) {
  16348. internalTexture = this.emptyTexture3D;
  16349. }
  16350. else {
  16351. internalTexture = this.emptyTexture;
  16352. }
  16353. if (!isPartOfTextureArray) {
  16354. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16355. }
  16356. var needToBind = true;
  16357. if (this._boundTexturesCache[channel] === internalTexture) {
  16358. this._moveBoundTextureOnTop(internalTexture);
  16359. if (!isPartOfTextureArray) {
  16360. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16361. }
  16362. needToBind = false;
  16363. }
  16364. this._activeChannel = channel;
  16365. if (internalTexture && internalTexture.is3D) {
  16366. if (needToBind) {
  16367. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16368. }
  16369. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16370. internalTexture._cachedWrapU = texture.wrapU;
  16371. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16372. }
  16373. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16374. internalTexture._cachedWrapV = texture.wrapV;
  16375. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16376. }
  16377. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16378. internalTexture._cachedWrapR = texture.wrapR;
  16379. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16380. }
  16381. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16382. }
  16383. else if (internalTexture && internalTexture.isCube) {
  16384. if (needToBind) {
  16385. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16386. }
  16387. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16388. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16389. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16390. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16392. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16393. }
  16394. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16395. }
  16396. else {
  16397. if (needToBind) {
  16398. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16401. internalTexture._cachedWrapU = texture.wrapU;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16403. }
  16404. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16405. internalTexture._cachedWrapV = texture.wrapV;
  16406. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16407. }
  16408. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16409. }
  16410. return true;
  16411. };
  16412. /**
  16413. * Sets an array of texture to the webGL context
  16414. * @param channel defines the channel where the texture array must be set
  16415. * @param uniform defines the associated uniform location
  16416. * @param textures defines the array of textures to bind
  16417. */
  16418. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16419. if (channel < 0 || !uniform) {
  16420. return;
  16421. }
  16422. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16423. this._textureUnits = new Int32Array(textures.length);
  16424. }
  16425. for (var i = 0; i < textures.length; i++) {
  16426. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16427. }
  16428. this._gl.uniform1iv(uniform, this._textureUnits);
  16429. for (var index = 0; index < textures.length; index++) {
  16430. this._setTexture(this._textureUnits[index], textures[index], true);
  16431. }
  16432. };
  16433. /** @hidden */
  16434. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16435. var internalTexture = texture.getInternalTexture();
  16436. if (!internalTexture) {
  16437. return;
  16438. }
  16439. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16440. var value = texture.anisotropicFilteringLevel;
  16441. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16442. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16443. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16444. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16445. }
  16446. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16447. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16448. internalTexture._cachedAnisotropicFilteringLevel = value;
  16449. }
  16450. };
  16451. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16452. this._bindTextureDirectly(target, texture, true, true);
  16453. this._gl.texParameterf(target, parameter, value);
  16454. };
  16455. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16456. if (texture) {
  16457. this._bindTextureDirectly(target, texture, true, true);
  16458. }
  16459. this._gl.texParameteri(target, parameter, value);
  16460. };
  16461. /**
  16462. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16463. * @param x defines the x coordinate of the rectangle where pixels must be read
  16464. * @param y defines the y coordinate of the rectangle where pixels must be read
  16465. * @param width defines the width of the rectangle where pixels must be read
  16466. * @param height defines the height of the rectangle where pixels must be read
  16467. * @returns a Uint8Array containing RGBA colors
  16468. */
  16469. Engine.prototype.readPixels = function (x, y, width, height) {
  16470. var data = new Uint8Array(height * width * 4);
  16471. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16472. return data;
  16473. };
  16474. /**
  16475. * Add an externaly attached data from its key.
  16476. * This method call will fail and return false, if such key already exists.
  16477. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16478. * @param key the unique key that identifies the data
  16479. * @param data the data object to associate to the key for this Engine instance
  16480. * @return true if no such key were already present and the data was added successfully, false otherwise
  16481. */
  16482. Engine.prototype.addExternalData = function (key, data) {
  16483. if (!this._externalData) {
  16484. this._externalData = new BABYLON.StringDictionary();
  16485. }
  16486. return this._externalData.add(key, data);
  16487. };
  16488. /**
  16489. * Get an externaly attached data from its key
  16490. * @param key the unique key that identifies the data
  16491. * @return the associated data, if present (can be null), or undefined if not present
  16492. */
  16493. Engine.prototype.getExternalData = function (key) {
  16494. if (!this._externalData) {
  16495. this._externalData = new BABYLON.StringDictionary();
  16496. }
  16497. return this._externalData.get(key);
  16498. };
  16499. /**
  16500. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16501. * @param key the unique key that identifies the data
  16502. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16503. * @return the associated data, can be null if the factory returned null.
  16504. */
  16505. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.getOrAddWithFactory(key, factory);
  16510. };
  16511. /**
  16512. * Remove an externaly attached data from the Engine instance
  16513. * @param key the unique key that identifies the data
  16514. * @return true if the data was successfully removed, false if it doesn't exist
  16515. */
  16516. Engine.prototype.removeExternalData = function (key) {
  16517. if (!this._externalData) {
  16518. this._externalData = new BABYLON.StringDictionary();
  16519. }
  16520. return this._externalData.remove(key);
  16521. };
  16522. /**
  16523. * Unbind all vertex attributes from the webGL context
  16524. */
  16525. Engine.prototype.unbindAllAttributes = function () {
  16526. if (this._mustWipeVertexAttributes) {
  16527. this._mustWipeVertexAttributes = false;
  16528. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16529. this._gl.disableVertexAttribArray(i);
  16530. this._vertexAttribArraysEnabled[i] = false;
  16531. this._currentBufferPointers[i].active = false;
  16532. }
  16533. return;
  16534. }
  16535. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16536. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16537. continue;
  16538. }
  16539. this._gl.disableVertexAttribArray(i);
  16540. this._vertexAttribArraysEnabled[i] = false;
  16541. this._currentBufferPointers[i].active = false;
  16542. }
  16543. };
  16544. /**
  16545. * 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
  16546. */
  16547. Engine.prototype.releaseEffects = function () {
  16548. for (var name in this._compiledEffects) {
  16549. this._deleteProgram(this._compiledEffects[name]._program);
  16550. }
  16551. this._compiledEffects = {};
  16552. };
  16553. /**
  16554. * Dispose and release all associated resources
  16555. */
  16556. Engine.prototype.dispose = function () {
  16557. this.hideLoadingUI();
  16558. this.stopRenderLoop();
  16559. // Release postProcesses
  16560. while (this.postProcesses.length) {
  16561. this.postProcesses[0].dispose();
  16562. }
  16563. // Empty texture
  16564. if (this._emptyTexture) {
  16565. this._releaseTexture(this._emptyTexture);
  16566. this._emptyTexture = null;
  16567. }
  16568. if (this._emptyCubeTexture) {
  16569. this._releaseTexture(this._emptyCubeTexture);
  16570. this._emptyCubeTexture = null;
  16571. }
  16572. // Rescale PP
  16573. if (this._rescalePostProcess) {
  16574. this._rescalePostProcess.dispose();
  16575. }
  16576. // Release scenes
  16577. while (this.scenes.length) {
  16578. this.scenes[0].dispose();
  16579. }
  16580. // Release audio engine
  16581. if (Engine.audioEngine) {
  16582. Engine.audioEngine.dispose();
  16583. }
  16584. // Release effects
  16585. this.releaseEffects();
  16586. // Unbind
  16587. this.unbindAllAttributes();
  16588. this._boundUniforms = [];
  16589. if (this._dummyFramebuffer) {
  16590. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16591. }
  16592. //WebVR
  16593. this.disableVR();
  16594. // Events
  16595. if (BABYLON.Tools.IsWindowObjectExist()) {
  16596. window.removeEventListener("blur", this._onBlur);
  16597. window.removeEventListener("focus", this._onFocus);
  16598. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16599. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16600. if (this._renderingCanvas) {
  16601. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16602. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16603. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16604. if (!this._doNotHandleContextLost) {
  16605. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16606. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16607. }
  16608. }
  16609. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16610. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16611. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16612. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16613. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16614. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16615. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16616. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16617. if (this._onVrDisplayConnect) {
  16618. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16619. if (this._onVrDisplayDisconnect) {
  16620. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16621. }
  16622. if (this._onVrDisplayPresentChange) {
  16623. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16624. }
  16625. this._onVrDisplayConnect = null;
  16626. this._onVrDisplayDisconnect = null;
  16627. }
  16628. }
  16629. // Remove from Instances
  16630. var index = Engine.Instances.indexOf(this);
  16631. if (index >= 0) {
  16632. Engine.Instances.splice(index, 1);
  16633. }
  16634. this._workingCanvas = null;
  16635. this._workingContext = null;
  16636. this._currentBufferPointers = [];
  16637. this._renderingCanvas = null;
  16638. this._currentProgram = null;
  16639. this._bindedRenderFunction = null;
  16640. this.onResizeObservable.clear();
  16641. this.onCanvasBlurObservable.clear();
  16642. this.onCanvasFocusObservable.clear();
  16643. this.onCanvasPointerOutObservable.clear();
  16644. this.onBeginFrameObservable.clear();
  16645. this.onEndFrameObservable.clear();
  16646. BABYLON.Effect.ResetCache();
  16647. // Abort active requests
  16648. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16649. var request = _a[_i];
  16650. request.abort();
  16651. }
  16652. };
  16653. // Loading screen
  16654. /**
  16655. * Display the loading screen
  16656. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16657. */
  16658. Engine.prototype.displayLoadingUI = function () {
  16659. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16660. return;
  16661. }
  16662. var loadingScreen = this.loadingScreen;
  16663. if (loadingScreen) {
  16664. loadingScreen.displayLoadingUI();
  16665. }
  16666. };
  16667. /**
  16668. * Hide the loading screen
  16669. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16670. */
  16671. Engine.prototype.hideLoadingUI = function () {
  16672. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16673. return;
  16674. }
  16675. var loadingScreen = this.loadingScreen;
  16676. if (loadingScreen) {
  16677. loadingScreen.hideLoadingUI();
  16678. }
  16679. };
  16680. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16681. /**
  16682. * Gets the current loading screen object
  16683. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16684. */
  16685. get: function () {
  16686. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16687. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16688. return this._loadingScreen;
  16689. },
  16690. /**
  16691. * Sets the current loading screen object
  16692. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16693. */
  16694. set: function (loadingScreen) {
  16695. this._loadingScreen = loadingScreen;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16701. /**
  16702. * Sets the current loading screen text
  16703. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16704. */
  16705. set: function (text) {
  16706. this.loadingScreen.loadingUIText = text;
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16712. /**
  16713. * Sets the current loading screen background color
  16714. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16715. */
  16716. set: function (color) {
  16717. this.loadingScreen.loadingUIBackgroundColor = color;
  16718. },
  16719. enumerable: true,
  16720. configurable: true
  16721. });
  16722. /**
  16723. * Attach a new callback raised when context lost event is fired
  16724. * @param callback defines the callback to call
  16725. */
  16726. Engine.prototype.attachContextLostEvent = function (callback) {
  16727. if (this._renderingCanvas) {
  16728. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16729. }
  16730. };
  16731. /**
  16732. * Attach a new callback raised when context restored event is fired
  16733. * @param callback defines the callback to call
  16734. */
  16735. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16736. if (this._renderingCanvas) {
  16737. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16738. }
  16739. };
  16740. /**
  16741. * Gets the source code of the vertex shader associated with a specific webGL program
  16742. * @param program defines the program to use
  16743. * @returns a string containing the source code of the vertex shader associated with the program
  16744. */
  16745. Engine.prototype.getVertexShaderSource = function (program) {
  16746. var shaders = this._gl.getAttachedShaders(program);
  16747. if (!shaders) {
  16748. return null;
  16749. }
  16750. return this._gl.getShaderSource(shaders[0]);
  16751. };
  16752. /**
  16753. * Gets the source code of the fragment shader associated with a specific webGL program
  16754. * @param program defines the program to use
  16755. * @returns a string containing the source code of the fragment shader associated with the program
  16756. */
  16757. Engine.prototype.getFragmentShaderSource = function (program) {
  16758. var shaders = this._gl.getAttachedShaders(program);
  16759. if (!shaders) {
  16760. return null;
  16761. }
  16762. return this._gl.getShaderSource(shaders[1]);
  16763. };
  16764. /**
  16765. * Get the current error code of the webGL context
  16766. * @returns the error code
  16767. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16768. */
  16769. Engine.prototype.getError = function () {
  16770. return this._gl.getError();
  16771. };
  16772. // FPS
  16773. /**
  16774. * Gets the current framerate
  16775. * @returns a number representing the framerate
  16776. */
  16777. Engine.prototype.getFps = function () {
  16778. return this._fps;
  16779. };
  16780. /**
  16781. * Gets the time spent between current and previous frame
  16782. * @returns a number representing the delta time in ms
  16783. */
  16784. Engine.prototype.getDeltaTime = function () {
  16785. return this._deltaTime;
  16786. };
  16787. Engine.prototype._measureFps = function () {
  16788. this._performanceMonitor.sampleFrame();
  16789. this._fps = this._performanceMonitor.averageFPS;
  16790. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16791. };
  16792. /** @hidden */
  16793. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16794. if (faceIndex === void 0) { faceIndex = -1; }
  16795. if (level === void 0) { level = 0; }
  16796. var gl = this._gl;
  16797. if (!this._dummyFramebuffer) {
  16798. var dummy = gl.createFramebuffer();
  16799. if (!dummy) {
  16800. throw new Error("Unable to create dummy framebuffer");
  16801. }
  16802. this._dummyFramebuffer = dummy;
  16803. }
  16804. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16805. if (faceIndex > -1) {
  16806. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16807. }
  16808. else {
  16809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16810. }
  16811. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16812. var buffer;
  16813. switch (readType) {
  16814. case gl.UNSIGNED_BYTE:
  16815. buffer = new Uint8Array(4 * width * height);
  16816. readType = gl.UNSIGNED_BYTE;
  16817. break;
  16818. default:
  16819. buffer = new Float32Array(4 * width * height);
  16820. readType = gl.FLOAT;
  16821. break;
  16822. }
  16823. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16824. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16825. return buffer;
  16826. };
  16827. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16828. if (this._webGLVersion > 1) {
  16829. return this._caps.colorBufferFloat;
  16830. }
  16831. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16832. };
  16833. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16834. if (this._webGLVersion > 1) {
  16835. return this._caps.colorBufferFloat;
  16836. }
  16837. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16838. };
  16839. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16840. Engine.prototype._canRenderToFramebuffer = function (type) {
  16841. var gl = this._gl;
  16842. //clear existing errors
  16843. while (gl.getError() !== gl.NO_ERROR) { }
  16844. var successful = true;
  16845. var texture = gl.createTexture();
  16846. gl.bindTexture(gl.TEXTURE_2D, texture);
  16847. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16848. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16850. var fb = gl.createFramebuffer();
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16853. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16854. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16855. successful = successful && (gl.getError() === gl.NO_ERROR);
  16856. //try render by clearing frame buffer's color buffer
  16857. if (successful) {
  16858. gl.clear(gl.COLOR_BUFFER_BIT);
  16859. successful = successful && (gl.getError() === gl.NO_ERROR);
  16860. }
  16861. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16862. if (successful) {
  16863. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16864. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16865. var readFormat = gl.RGBA;
  16866. var readType = gl.UNSIGNED_BYTE;
  16867. var buffer = new Uint8Array(4);
  16868. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16869. successful = successful && (gl.getError() === gl.NO_ERROR);
  16870. }
  16871. //clean up
  16872. gl.deleteTexture(texture);
  16873. gl.deleteFramebuffer(fb);
  16874. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16875. //clear accumulated errors
  16876. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16877. return successful;
  16878. };
  16879. /** @hidden */
  16880. Engine.prototype._getWebGLTextureType = function (type) {
  16881. if (type === Engine.TEXTURETYPE_FLOAT) {
  16882. return this._gl.FLOAT;
  16883. }
  16884. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16885. // Add Half Float Constant.
  16886. return this._gl.HALF_FLOAT_OES;
  16887. }
  16888. return this._gl.UNSIGNED_BYTE;
  16889. };
  16890. ;
  16891. Engine.prototype._getInternalFormat = function (format) {
  16892. var internalFormat = this._gl.RGBA;
  16893. switch (format) {
  16894. case Engine.TEXTUREFORMAT_ALPHA:
  16895. internalFormat = this._gl.ALPHA;
  16896. break;
  16897. case Engine.TEXTUREFORMAT_LUMINANCE:
  16898. internalFormat = this._gl.LUMINANCE;
  16899. break;
  16900. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16901. internalFormat = this._gl.LUMINANCE_ALPHA;
  16902. break;
  16903. case Engine.TEXTUREFORMAT_RGB:
  16904. internalFormat = this._gl.RGB;
  16905. break;
  16906. case Engine.TEXTUREFORMAT_RGBA:
  16907. internalFormat = this._gl.RGBA;
  16908. break;
  16909. case Engine.TEXTUREFORMAT_R:
  16910. internalFormat = this._gl.RED;
  16911. break;
  16912. case Engine.TEXTUREFORMAT_RG:
  16913. internalFormat = this._gl.RG;
  16914. break;
  16915. }
  16916. return internalFormat;
  16917. };
  16918. /** @hidden */
  16919. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16920. if (this._webGLVersion === 1) {
  16921. if (format !== undefined) {
  16922. switch (format) {
  16923. case Engine.TEXTUREFORMAT_LUMINANCE:
  16924. return this._gl.LUMINANCE;
  16925. case Engine.TEXTUREFORMAT_ALPHA:
  16926. return this._gl.ALPHA;
  16927. }
  16928. }
  16929. return this._gl.RGBA;
  16930. }
  16931. if (type === Engine.TEXTURETYPE_FLOAT) {
  16932. if (format !== undefined) {
  16933. switch (format) {
  16934. case Engine.TEXTUREFORMAT_R:
  16935. return this._gl.R32F;
  16936. case Engine.TEXTUREFORMAT_RG:
  16937. return this._gl.RG32F;
  16938. case Engine.TEXTUREFORMAT_RGB:
  16939. return this._gl.RGB32F;
  16940. }
  16941. }
  16942. return this._gl.RGBA32F;
  16943. }
  16944. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16945. if (format) {
  16946. switch (format) {
  16947. case Engine.TEXTUREFORMAT_R:
  16948. return this._gl.R16F;
  16949. case Engine.TEXTUREFORMAT_RG:
  16950. return this._gl.RG16F;
  16951. case Engine.TEXTUREFORMAT_RGB:
  16952. return this._gl.RGB16F;
  16953. }
  16954. }
  16955. return this._gl.RGBA16F;
  16956. }
  16957. if (format !== undefined) {
  16958. switch (format) {
  16959. case Engine.TEXTUREFORMAT_LUMINANCE:
  16960. return this._gl.LUMINANCE;
  16961. case Engine.TEXTUREFORMAT_RGB:
  16962. return this._gl.RGB;
  16963. case Engine.TEXTUREFORMAT_R:
  16964. return this._gl.R8;
  16965. case Engine.TEXTUREFORMAT_RG:
  16966. return this._gl.RG8;
  16967. case Engine.TEXTUREFORMAT_ALPHA:
  16968. return this._gl.ALPHA;
  16969. }
  16970. }
  16971. return this._gl.RGBA;
  16972. };
  16973. ;
  16974. /** @hidden */
  16975. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16976. if (type === Engine.TEXTURETYPE_FLOAT) {
  16977. return this._gl.RGBA32F;
  16978. }
  16979. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16980. return this._gl.RGBA16F;
  16981. }
  16982. return this._gl.RGBA8;
  16983. };
  16984. ;
  16985. // Transform feedback
  16986. /**
  16987. * Creates a webGL transform feedback object
  16988. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16989. * @returns the webGL transform feedback object
  16990. */
  16991. Engine.prototype.createTransformFeedback = function () {
  16992. return this._gl.createTransformFeedback();
  16993. };
  16994. /**
  16995. * Delete a webGL transform feedback object
  16996. * @param value defines the webGL transform feedback object to delete
  16997. */
  16998. Engine.prototype.deleteTransformFeedback = function (value) {
  16999. this._gl.deleteTransformFeedback(value);
  17000. };
  17001. /**
  17002. * Bind a webGL transform feedback object to the webgl context
  17003. * @param value defines the webGL transform feedback object to bind
  17004. */
  17005. Engine.prototype.bindTransformFeedback = function (value) {
  17006. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17007. };
  17008. /**
  17009. * Begins a transform feedback operation
  17010. * @param usePoints defines if points or triangles must be used
  17011. */
  17012. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17013. if (usePoints === void 0) { usePoints = true; }
  17014. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17015. };
  17016. /**
  17017. * Ends a transform feedback operation
  17018. */
  17019. Engine.prototype.endTransformFeedback = function () {
  17020. this._gl.endTransformFeedback();
  17021. };
  17022. /**
  17023. * Specify the varyings to use with transform feedback
  17024. * @param program defines the associated webGL program
  17025. * @param value defines the list of strings representing the varying names
  17026. */
  17027. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17028. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17029. };
  17030. /**
  17031. * Bind a webGL buffer for a transform feedback operation
  17032. * @param value defines the webGL buffer to bind
  17033. */
  17034. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17035. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17036. };
  17037. /** @hidden */
  17038. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17039. var _this = this;
  17040. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17041. this._activeRequests.push(request);
  17042. request.onCompleteObservable.add(function (request) {
  17043. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17044. });
  17045. return request;
  17046. };
  17047. /** @hidden */
  17048. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17049. var _this = this;
  17050. return new Promise(function (resolve, reject) {
  17051. _this._loadFile(url, function (data) {
  17052. resolve(data);
  17053. }, undefined, database, useArrayBuffer, function (request, exception) {
  17054. reject(exception);
  17055. });
  17056. });
  17057. };
  17058. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17059. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17060. var onload = function (data) {
  17061. loadedFiles[index] = data;
  17062. loadedFiles._internalCount++;
  17063. if (loadedFiles._internalCount === 6) {
  17064. onfinish(loadedFiles);
  17065. }
  17066. };
  17067. var onerror = function (request, exception) {
  17068. if (onErrorCallBack && request) {
  17069. onErrorCallBack(request.status + " " + request.statusText, exception);
  17070. }
  17071. };
  17072. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17073. };
  17074. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17075. if (onError === void 0) { onError = null; }
  17076. var loadedFiles = [];
  17077. loadedFiles._internalCount = 0;
  17078. for (var index = 0; index < 6; index++) {
  17079. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17080. }
  17081. };
  17082. // Statics
  17083. /**
  17084. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17085. * @returns true if the engine can be created
  17086. * @ignorenaming
  17087. */
  17088. Engine.isSupported = function () {
  17089. try {
  17090. var tempcanvas = document.createElement("canvas");
  17091. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17092. return gl != null && !!window.WebGLRenderingContext;
  17093. }
  17094. catch (e) {
  17095. return false;
  17096. }
  17097. };
  17098. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17099. Engine.ExceptionList = [
  17100. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17101. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17102. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17103. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17104. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17105. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17106. ];
  17107. /** Gets the list of created engines */
  17108. Engine.Instances = new Array();
  17109. // Const statics
  17110. /** Defines that alpha blending is disabled */
  17111. Engine.ALPHA_DISABLE = 0;
  17112. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17113. Engine.ALPHA_ADD = 1;
  17114. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17115. Engine.ALPHA_COMBINE = 2;
  17116. /** Defines that alpha blending to DEST - SRC * DEST */
  17117. Engine.ALPHA_SUBTRACT = 3;
  17118. /** Defines that alpha blending to SRC * DEST */
  17119. Engine.ALPHA_MULTIPLY = 4;
  17120. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17121. Engine.ALPHA_MAXIMIZED = 5;
  17122. /** Defines that alpha blending to SRC + DEST */
  17123. Engine.ALPHA_ONEONE = 6;
  17124. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17125. Engine.ALPHA_PREMULTIPLIED = 7;
  17126. /**
  17127. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17128. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17129. */
  17130. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17131. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17132. Engine.ALPHA_INTERPOLATE = 9;
  17133. /**
  17134. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17135. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17136. */
  17137. Engine.ALPHA_SCREENMODE = 10;
  17138. /** Defines that the ressource is not delayed*/
  17139. Engine.DELAYLOADSTATE_NONE = 0;
  17140. /** Defines that the ressource was successfully delay loaded */
  17141. Engine.DELAYLOADSTATE_LOADED = 1;
  17142. /** Defines that the ressource is currently delay loading */
  17143. Engine.DELAYLOADSTATE_LOADING = 2;
  17144. /** Defines that the ressource is delayed and has not started loading */
  17145. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17146. // Depht or Stencil test Constants.
  17147. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17148. Engine.NEVER = 0x0200;
  17149. /** 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 */
  17150. Engine.ALWAYS = 0x0207;
  17151. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17152. Engine.LESS = 0x0201;
  17153. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17154. Engine.EQUAL = 0x0202;
  17155. /** 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 */
  17156. Engine.LEQUAL = 0x0203;
  17157. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17158. Engine.GREATER = 0x0204;
  17159. /** 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 */
  17160. Engine.GEQUAL = 0x0206;
  17161. /** 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 */
  17162. Engine.NOTEQUAL = 0x0205;
  17163. // Stencil Actions Constants.
  17164. /** Passed to stencilOperation to specify that stencil value must be kept */
  17165. Engine.KEEP = 0x1E00;
  17166. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17167. Engine.REPLACE = 0x1E01;
  17168. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17169. Engine.INCR = 0x1E02;
  17170. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17171. Engine.DECR = 0x1E03;
  17172. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17173. Engine.INVERT = 0x150A;
  17174. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17175. Engine.INCR_WRAP = 0x8507;
  17176. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17177. Engine.DECR_WRAP = 0x8508;
  17178. /** Texture is not repeating outside of 0..1 UVs */
  17179. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17180. /** Texture is repeating outside of 0..1 UVs */
  17181. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17182. /** Texture is repeating and mirrored */
  17183. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17184. /** ALPHA */
  17185. Engine.TEXTUREFORMAT_ALPHA = 0;
  17186. /** LUMINANCE */
  17187. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17188. /** LUMINANCE_ALPHA */
  17189. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17190. /** RGB */
  17191. Engine.TEXTUREFORMAT_RGB = 4;
  17192. /** RGBA */
  17193. Engine.TEXTUREFORMAT_RGBA = 5;
  17194. /** R */
  17195. Engine.TEXTUREFORMAT_R = 6;
  17196. /** RG */
  17197. Engine.TEXTUREFORMAT_RG = 7;
  17198. /** UNSIGNED_INT */
  17199. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17200. /** FLOAT */
  17201. Engine.TEXTURETYPE_FLOAT = 1;
  17202. /** HALF_FLOAT */
  17203. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17204. /** nearest is mag = nearest and min = nearest and mip = linear */
  17205. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17206. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17207. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17208. /** Trilinear is mag = linear and min = linear and mip = linear */
  17209. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17210. /** nearest is mag = nearest and min = nearest and mip = linear */
  17211. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17212. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17213. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17214. /** Trilinear is mag = linear and min = linear and mip = linear */
  17215. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17216. /** mag = nearest and min = nearest and mip = nearest */
  17217. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17218. /** mag = nearest and min = linear and mip = nearest */
  17219. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17220. /** mag = nearest and min = linear and mip = linear */
  17221. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17222. /** mag = nearest and min = linear and mip = none */
  17223. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17224. /** mag = nearest and min = nearest and mip = none */
  17225. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17226. /** mag = linear and min = nearest and mip = nearest */
  17227. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17228. /** mag = linear and min = nearest and mip = linear */
  17229. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17230. /** mag = linear and min = linear and mip = none */
  17231. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17232. /** mag = linear and min = nearest and mip = none */
  17233. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17234. /** Explicit coordinates mode */
  17235. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17236. /** Spherical coordinates mode */
  17237. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17238. /** Planar coordinates mode */
  17239. Engine.TEXTURE_PLANAR_MODE = 2;
  17240. /** Cubic coordinates mode */
  17241. Engine.TEXTURE_CUBIC_MODE = 3;
  17242. /** Projection coordinates mode */
  17243. Engine.TEXTURE_PROJECTION_MODE = 4;
  17244. /** Skybox coordinates mode */
  17245. Engine.TEXTURE_SKYBOX_MODE = 5;
  17246. /** Inverse Cubic coordinates mode */
  17247. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17248. /** Equirectangular coordinates mode */
  17249. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17250. /** Equirectangular Fixed coordinates mode */
  17251. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17252. /** Equirectangular Fixed Mirrored coordinates mode */
  17253. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17254. // Texture rescaling mode
  17255. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17256. Engine.SCALEMODE_FLOOR = 1;
  17257. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17258. Engine.SCALEMODE_NEAREST = 2;
  17259. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17260. Engine.SCALEMODE_CEILING = 3;
  17261. // Updatable statics so stick with vars here
  17262. /**
  17263. * Gets or sets the epsilon value used by collision engine
  17264. */
  17265. Engine.CollisionsEpsilon = 0.001;
  17266. /**
  17267. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17268. */
  17269. Engine.CodeRepository = "src/";
  17270. /**
  17271. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17272. */
  17273. Engine.ShadersRepository = "src/Shaders/";
  17274. return Engine;
  17275. }());
  17276. BABYLON.Engine = Engine;
  17277. })(BABYLON || (BABYLON = {}));
  17278. //# sourceMappingURL=babylon.engine.js.map
  17279. var BABYLON;
  17280. (function (BABYLON) {
  17281. /**
  17282. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17283. */
  17284. var Node = /** @class */ (function () {
  17285. /**
  17286. * Creates a new Node
  17287. * @param {string} name - the name and id to be given to this node
  17288. * @param {BABYLON.Scene} the scene this node will be added to
  17289. */
  17290. function Node(name, scene) {
  17291. if (scene === void 0) { scene = null; }
  17292. /**
  17293. * Gets or sets a string used to store user defined state for the node
  17294. */
  17295. this.state = "";
  17296. /**
  17297. * Gets or sets an object used to store user defined information for the node
  17298. */
  17299. this.metadata = null;
  17300. /**
  17301. * Gets or sets a boolean used to define if the node must be serialized
  17302. */
  17303. this.doNotSerialize = false;
  17304. /** @hidden */
  17305. this._isDisposed = false;
  17306. /**
  17307. * Gets a list of Animations associated with the node
  17308. */
  17309. this.animations = new Array();
  17310. this._ranges = {};
  17311. this._isEnabled = true;
  17312. this._isReady = true;
  17313. /** @hidden */
  17314. this._currentRenderId = -1;
  17315. this._parentRenderId = -1;
  17316. this._childRenderId = -1;
  17317. this._animationPropertiesOverride = null;
  17318. /**
  17319. * An event triggered when the mesh is disposed
  17320. */
  17321. this.onDisposeObservable = new BABYLON.Observable();
  17322. // Behaviors
  17323. this._behaviors = new Array();
  17324. this.name = name;
  17325. this.id = name;
  17326. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17327. this.uniqueId = this._scene.getUniqueId();
  17328. this._initCache();
  17329. }
  17330. /**
  17331. * Add a new node constructor
  17332. * @param type defines the type name of the node to construct
  17333. * @param constructorFunc defines the constructor function
  17334. */
  17335. Node.AddNodeConstructor = function (type, constructorFunc) {
  17336. this._NodeConstructors[type] = constructorFunc;
  17337. };
  17338. /**
  17339. * Returns a node constructor based on type name
  17340. * @param type defines the type name
  17341. * @param name defines the new node name
  17342. * @param scene defines the hosting scene
  17343. * @param options defines optional options to transmit to constructors
  17344. * @returns the new constructor or null
  17345. */
  17346. Node.Construct = function (type, name, scene, options) {
  17347. var constructorFunc = this._NodeConstructors[type];
  17348. if (!constructorFunc) {
  17349. return null;
  17350. }
  17351. return constructorFunc(name, scene, options);
  17352. };
  17353. /**
  17354. * Gets a boolean indicating if the node has been disposed
  17355. * @returns true if the node was disposed
  17356. */
  17357. Node.prototype.isDisposed = function () {
  17358. return this._isDisposed;
  17359. };
  17360. Object.defineProperty(Node.prototype, "parent", {
  17361. get: function () {
  17362. return this._parentNode;
  17363. },
  17364. /**
  17365. * Gets or sets the parent of the node
  17366. */
  17367. set: function (parent) {
  17368. if (this._parentNode === parent) {
  17369. return;
  17370. }
  17371. // Remove self from list of children of parent
  17372. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17373. var index = this._parentNode._children.indexOf(this);
  17374. if (index !== -1) {
  17375. this._parentNode._children.splice(index, 1);
  17376. }
  17377. }
  17378. // Store new parent
  17379. this._parentNode = parent;
  17380. // Add as child to new parent
  17381. if (this._parentNode) {
  17382. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17383. this._parentNode._children = new Array();
  17384. }
  17385. this._parentNode._children.push(this);
  17386. }
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17392. /**
  17393. * Gets or sets the animation properties override
  17394. */
  17395. get: function () {
  17396. if (!this._animationPropertiesOverride) {
  17397. return this._scene.animationPropertiesOverride;
  17398. }
  17399. return this._animationPropertiesOverride;
  17400. },
  17401. set: function (value) {
  17402. this._animationPropertiesOverride = value;
  17403. },
  17404. enumerable: true,
  17405. configurable: true
  17406. });
  17407. /**
  17408. * Gets a string idenfifying the name of the class
  17409. * @returns "Node" string
  17410. */
  17411. Node.prototype.getClassName = function () {
  17412. return "Node";
  17413. };
  17414. Object.defineProperty(Node.prototype, "onDispose", {
  17415. /**
  17416. * Sets a callback that will be raised when the node will be disposed
  17417. */
  17418. set: function (callback) {
  17419. if (this._onDisposeObserver) {
  17420. this.onDisposeObservable.remove(this._onDisposeObserver);
  17421. }
  17422. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. /**
  17428. * Gets the scene of the node
  17429. * @returns a {BABYLON.Scene}
  17430. */
  17431. Node.prototype.getScene = function () {
  17432. return this._scene;
  17433. };
  17434. /**
  17435. * Gets the engine of the node
  17436. * @returns a {BABYLON.Engine}
  17437. */
  17438. Node.prototype.getEngine = function () {
  17439. return this._scene.getEngine();
  17440. };
  17441. /**
  17442. * Attach a behavior to the node
  17443. * @see http://doc.babylonjs.com/features/behaviour
  17444. * @param behavior defines the behavior to attach
  17445. * @returns the current Node
  17446. */
  17447. Node.prototype.addBehavior = function (behavior) {
  17448. var _this = this;
  17449. var index = this._behaviors.indexOf(behavior);
  17450. if (index !== -1) {
  17451. return this;
  17452. }
  17453. behavior.init();
  17454. if (this._scene.isLoading) {
  17455. // We defer the attach when the scene will be loaded
  17456. this._scene.onDataLoadedObservable.addOnce(function () {
  17457. behavior.attach(_this);
  17458. });
  17459. }
  17460. else {
  17461. behavior.attach(this);
  17462. }
  17463. this._behaviors.push(behavior);
  17464. return this;
  17465. };
  17466. /**
  17467. * Remove an attached behavior
  17468. * @see http://doc.babylonjs.com/features/behaviour
  17469. * @param behavior defines the behavior to attach
  17470. * @returns the current Node
  17471. */
  17472. Node.prototype.removeBehavior = function (behavior) {
  17473. var index = this._behaviors.indexOf(behavior);
  17474. if (index === -1) {
  17475. return this;
  17476. }
  17477. this._behaviors[index].detach();
  17478. this._behaviors.splice(index, 1);
  17479. return this;
  17480. };
  17481. Object.defineProperty(Node.prototype, "behaviors", {
  17482. /**
  17483. * Gets the list of attached behaviors
  17484. * @see http://doc.babylonjs.com/features/behaviour
  17485. */
  17486. get: function () {
  17487. return this._behaviors;
  17488. },
  17489. enumerable: true,
  17490. configurable: true
  17491. });
  17492. /**
  17493. * Gets an attached behavior by name
  17494. * @param name defines the name of the behavior to look for
  17495. * @see http://doc.babylonjs.com/features/behaviour
  17496. * @returns null if behavior was not found else the requested behavior
  17497. */
  17498. Node.prototype.getBehaviorByName = function (name) {
  17499. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17500. var behavior = _a[_i];
  17501. if (behavior.name === name) {
  17502. return behavior;
  17503. }
  17504. }
  17505. return null;
  17506. };
  17507. /**
  17508. * Returns the world matrix of the node
  17509. * @returns a matrix containing the node's world matrix
  17510. */
  17511. Node.prototype.getWorldMatrix = function () {
  17512. return BABYLON.Matrix.Identity();
  17513. };
  17514. /** @hidden */
  17515. Node.prototype._getWorldMatrixDeterminant = function () {
  17516. return 1;
  17517. };
  17518. // override it in derived class if you add new variables to the cache
  17519. // and call the parent class method
  17520. /** @hidden */
  17521. Node.prototype._initCache = function () {
  17522. this._cache = {};
  17523. this._cache.parent = undefined;
  17524. };
  17525. /** @hidden */
  17526. Node.prototype.updateCache = function (force) {
  17527. if (!force && this.isSynchronized())
  17528. return;
  17529. this._cache.parent = this.parent;
  17530. this._updateCache();
  17531. };
  17532. // override it in derived class if you add new variables to the cache
  17533. // and call the parent class method if !ignoreParentClass
  17534. /** @hidden */
  17535. Node.prototype._updateCache = function (ignoreParentClass) {
  17536. };
  17537. // override it in derived class if you add new variables to the cache
  17538. /** @hidden */
  17539. Node.prototype._isSynchronized = function () {
  17540. return true;
  17541. };
  17542. /** @hidden */
  17543. Node.prototype._markSyncedWithParent = function () {
  17544. if (this.parent) {
  17545. this._parentRenderId = this.parent._childRenderId;
  17546. }
  17547. };
  17548. /** @hidden */
  17549. Node.prototype.isSynchronizedWithParent = function () {
  17550. if (!this.parent) {
  17551. return true;
  17552. }
  17553. if (this._parentRenderId !== this.parent._childRenderId) {
  17554. return false;
  17555. }
  17556. return this.parent.isSynchronized();
  17557. };
  17558. /** @hidden */
  17559. Node.prototype.isSynchronized = function (updateCache) {
  17560. var check = this.hasNewParent();
  17561. check = check || !this.isSynchronizedWithParent();
  17562. check = check || !this._isSynchronized();
  17563. if (updateCache)
  17564. this.updateCache(true);
  17565. return !check;
  17566. };
  17567. /** @hidden */
  17568. Node.prototype.hasNewParent = function (update) {
  17569. if (this._cache.parent === this.parent)
  17570. return false;
  17571. if (update)
  17572. this._cache.parent = this.parent;
  17573. return true;
  17574. };
  17575. /**
  17576. * Is this node ready to be used/rendered
  17577. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17578. * @return true if the node is ready
  17579. */
  17580. Node.prototype.isReady = function (completeCheck) {
  17581. if (completeCheck === void 0) { completeCheck = false; }
  17582. return this._isReady;
  17583. };
  17584. /**
  17585. * Is this node enabled?
  17586. * 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
  17587. * @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
  17588. * @return whether this node (and its parent) is enabled
  17589. */
  17590. Node.prototype.isEnabled = function (checkAncestors) {
  17591. if (checkAncestors === void 0) { checkAncestors = true; }
  17592. if (checkAncestors === false) {
  17593. return this._isEnabled;
  17594. }
  17595. if (this._isEnabled === false) {
  17596. return false;
  17597. }
  17598. if (this.parent !== undefined && this.parent !== null) {
  17599. return this.parent.isEnabled(checkAncestors);
  17600. }
  17601. return true;
  17602. };
  17603. /**
  17604. * Set the enabled state of this node
  17605. * @param value defines the new enabled state
  17606. */
  17607. Node.prototype.setEnabled = function (value) {
  17608. this._isEnabled = value;
  17609. };
  17610. /**
  17611. * Is this node a descendant of the given node?
  17612. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17613. * @param ancestor defines the parent node to inspect
  17614. * @returns a boolean indicating if this node is a descendant of the given node
  17615. */
  17616. Node.prototype.isDescendantOf = function (ancestor) {
  17617. if (this.parent) {
  17618. if (this.parent === ancestor) {
  17619. return true;
  17620. }
  17621. return this.parent.isDescendantOf(ancestor);
  17622. }
  17623. return false;
  17624. };
  17625. /** @hidden */
  17626. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17627. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17628. if (!this._children) {
  17629. return;
  17630. }
  17631. for (var index = 0; index < this._children.length; index++) {
  17632. var item = this._children[index];
  17633. if (!predicate || predicate(item)) {
  17634. results.push(item);
  17635. }
  17636. if (!directDescendantsOnly) {
  17637. item._getDescendants(results, false, predicate);
  17638. }
  17639. }
  17640. };
  17641. /**
  17642. * Will return all nodes that have this node as ascendant
  17643. * @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
  17644. * @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
  17645. * @return all children nodes of all types
  17646. */
  17647. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17648. var results = new Array();
  17649. this._getDescendants(results, directDescendantsOnly, predicate);
  17650. return results;
  17651. };
  17652. /**
  17653. * Get all child-meshes of this node
  17654. * @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
  17655. * @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
  17656. * @returns an array of {BABYLON.AbstractMesh}
  17657. */
  17658. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17659. var results = [];
  17660. this._getDescendants(results, directDescendantsOnly, function (node) {
  17661. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17662. });
  17663. return results;
  17664. };
  17665. /**
  17666. * Get all child-transformNodes of this node
  17667. * @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
  17668. * @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
  17669. * @returns an array of {BABYLON.TransformNode}
  17670. */
  17671. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17672. var results = [];
  17673. this._getDescendants(results, directDescendantsOnly, function (node) {
  17674. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17675. });
  17676. return results;
  17677. };
  17678. /**
  17679. * Get all direct children of this node
  17680. * @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
  17681. * @returns an array of {BABYLON.Node}
  17682. */
  17683. Node.prototype.getChildren = function (predicate) {
  17684. return this.getDescendants(true, predicate);
  17685. };
  17686. /** @hidden */
  17687. Node.prototype._setReady = function (state) {
  17688. if (state === this._isReady) {
  17689. return;
  17690. }
  17691. if (!state) {
  17692. this._isReady = false;
  17693. return;
  17694. }
  17695. if (this.onReady) {
  17696. this.onReady(this);
  17697. }
  17698. this._isReady = true;
  17699. };
  17700. /**
  17701. * Get an animation by name
  17702. * @param name defines the name of the animation to look for
  17703. * @returns null if not found else the requested animation
  17704. */
  17705. Node.prototype.getAnimationByName = function (name) {
  17706. for (var i = 0; i < this.animations.length; i++) {
  17707. var animation = this.animations[i];
  17708. if (animation.name === name) {
  17709. return animation;
  17710. }
  17711. }
  17712. return null;
  17713. };
  17714. /**
  17715. * Creates an animation range for this node
  17716. * @param name defines the name of the range
  17717. * @param from defines the starting key
  17718. * @param to defines the end key
  17719. */
  17720. Node.prototype.createAnimationRange = function (name, from, to) {
  17721. // check name not already in use
  17722. if (!this._ranges[name]) {
  17723. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17724. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17725. if (this.animations[i]) {
  17726. this.animations[i].createRange(name, from, to);
  17727. }
  17728. }
  17729. }
  17730. };
  17731. /**
  17732. * Delete a specific animation range
  17733. * @param name defines the name of the range to delete
  17734. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17735. */
  17736. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17737. if (deleteFrames === void 0) { deleteFrames = true; }
  17738. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17739. if (this.animations[i]) {
  17740. this.animations[i].deleteRange(name, deleteFrames);
  17741. }
  17742. }
  17743. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17744. };
  17745. /**
  17746. * Get an animation range by name
  17747. * @param name defines the name of the animation range to look for
  17748. * @returns null if not found else the requested animation range
  17749. */
  17750. Node.prototype.getAnimationRange = function (name) {
  17751. return this._ranges[name];
  17752. };
  17753. /**
  17754. * Will start the animation sequence
  17755. * @param name defines the range frames for animation sequence
  17756. * @param loop defines if the animation should loop (false by default)
  17757. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17758. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17759. * @returns the object created for this animation. If range does not exist, it will return null
  17760. */
  17761. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17762. var range = this.getAnimationRange(name);
  17763. if (!range) {
  17764. return null;
  17765. }
  17766. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17767. };
  17768. /**
  17769. * Serialize animation ranges into a JSON compatible object
  17770. * @returns serialization object
  17771. */
  17772. Node.prototype.serializeAnimationRanges = function () {
  17773. var serializationRanges = [];
  17774. for (var name in this._ranges) {
  17775. var localRange = this._ranges[name];
  17776. if (!localRange) {
  17777. continue;
  17778. }
  17779. var range = {};
  17780. range.name = name;
  17781. range.from = localRange.from;
  17782. range.to = localRange.to;
  17783. serializationRanges.push(range);
  17784. }
  17785. return serializationRanges;
  17786. };
  17787. /**
  17788. * Computes the world matrix of the node
  17789. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17790. * @returns the world matrix
  17791. */
  17792. Node.prototype.computeWorldMatrix = function (force) {
  17793. return BABYLON.Matrix.Identity();
  17794. };
  17795. /**
  17796. * Releases resources associated with this node.
  17797. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17798. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17799. */
  17800. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17801. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17802. if (!doNotRecurse) {
  17803. var nodes = this.getDescendants(true);
  17804. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17805. var node = nodes_1[_i];
  17806. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17807. }
  17808. }
  17809. else {
  17810. var transformNodes = this.getChildTransformNodes(true);
  17811. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17812. var transformNode = transformNodes_1[_a];
  17813. transformNode.parent = null;
  17814. transformNode.computeWorldMatrix(true);
  17815. }
  17816. }
  17817. this.parent = null;
  17818. // Callback
  17819. this.onDisposeObservable.notifyObservers(this);
  17820. this.onDisposeObservable.clear();
  17821. // Behaviors
  17822. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17823. var behavior = _c[_b];
  17824. behavior.detach();
  17825. }
  17826. this._behaviors = [];
  17827. this._isDisposed = true;
  17828. };
  17829. /**
  17830. * Parse animation range data from a serialization object and store them into a given node
  17831. * @param node defines where to store the animation ranges
  17832. * @param parsedNode defines the serialization object to read data from
  17833. * @param scene defines the hosting scene
  17834. */
  17835. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17836. if (parsedNode.ranges) {
  17837. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17838. var data = parsedNode.ranges[index];
  17839. node.createAnimationRange(data.name, data.from, data.to);
  17840. }
  17841. }
  17842. };
  17843. Node._NodeConstructors = {};
  17844. __decorate([
  17845. BABYLON.serialize()
  17846. ], Node.prototype, "name", void 0);
  17847. __decorate([
  17848. BABYLON.serialize()
  17849. ], Node.prototype, "id", void 0);
  17850. __decorate([
  17851. BABYLON.serialize()
  17852. ], Node.prototype, "uniqueId", void 0);
  17853. __decorate([
  17854. BABYLON.serialize()
  17855. ], Node.prototype, "state", void 0);
  17856. __decorate([
  17857. BABYLON.serialize()
  17858. ], Node.prototype, "metadata", void 0);
  17859. return Node;
  17860. }());
  17861. BABYLON.Node = Node;
  17862. })(BABYLON || (BABYLON = {}));
  17863. //# sourceMappingURL=babylon.node.js.map
  17864. var BABYLON;
  17865. (function (BABYLON) {
  17866. var BoundingSphere = /** @class */ (function () {
  17867. /**
  17868. * Creates a new bounding sphere
  17869. * @param min defines the minimum vector (in local space)
  17870. * @param max defines the maximum vector (in local space)
  17871. */
  17872. function BoundingSphere(min, max) {
  17873. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17874. this.reConstruct(min, max);
  17875. }
  17876. /**
  17877. * Recreates the entire bounding sphere from scratch
  17878. * @param min defines the new minimum vector (in local space)
  17879. * @param max defines the new maximum vector (in local space)
  17880. */
  17881. BoundingSphere.prototype.reConstruct = function (min, max) {
  17882. this.minimum = min.clone();
  17883. this.maximum = max.clone();
  17884. var distance = BABYLON.Vector3.Distance(min, max);
  17885. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17886. this.radius = distance * 0.5;
  17887. this.centerWorld = BABYLON.Vector3.Zero();
  17888. this._update(BABYLON.Matrix.Identity());
  17889. };
  17890. /**
  17891. * Scale the current bounding sphere by applying a scale factor
  17892. * @param factor defines the scale factor to apply
  17893. * @returns the current bounding box
  17894. */
  17895. BoundingSphere.prototype.scale = function (factor) {
  17896. var newRadius = this.radius * factor;
  17897. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17898. var min = this.center.subtract(newRadiusVector);
  17899. var max = this.center.add(newRadiusVector);
  17900. this.reConstruct(min, max);
  17901. return this;
  17902. };
  17903. // Methods
  17904. BoundingSphere.prototype._update = function (world) {
  17905. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17906. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17907. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17908. };
  17909. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17910. for (var i = 0; i < 6; i++) {
  17911. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17912. return false;
  17913. }
  17914. return true;
  17915. };
  17916. BoundingSphere.prototype.intersectsPoint = function (point) {
  17917. var x = this.centerWorld.x - point.x;
  17918. var y = this.centerWorld.y - point.y;
  17919. var z = this.centerWorld.z - point.z;
  17920. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17921. if (this.radiusWorld < distance)
  17922. return false;
  17923. return true;
  17924. };
  17925. // Statics
  17926. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17927. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17928. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17929. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17930. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17931. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17932. return false;
  17933. return true;
  17934. };
  17935. return BoundingSphere;
  17936. }());
  17937. BABYLON.BoundingSphere = BoundingSphere;
  17938. })(BABYLON || (BABYLON = {}));
  17939. //# sourceMappingURL=babylon.boundingSphere.js.map
  17940. var BABYLON;
  17941. (function (BABYLON) {
  17942. var BoundingBox = /** @class */ (function () {
  17943. /**
  17944. * Creates a new bounding box
  17945. * @param min defines the minimum vector (in local space)
  17946. * @param max defines the maximum vector (in local space)
  17947. */
  17948. function BoundingBox(min, max) {
  17949. this.vectorsWorld = new Array();
  17950. this.reConstruct(min, max);
  17951. }
  17952. // Methods
  17953. /**
  17954. * Recreates the entire bounding box from scratch
  17955. * @param min defines the new minimum vector (in local space)
  17956. * @param max defines the new maximum vector (in local space)
  17957. */
  17958. BoundingBox.prototype.reConstruct = function (min, max) {
  17959. this.minimum = min.clone();
  17960. this.maximum = max.clone();
  17961. // Bounding vectors
  17962. this.vectors = new Array();
  17963. this.vectors.push(this.minimum.clone());
  17964. this.vectors.push(this.maximum.clone());
  17965. this.vectors.push(this.minimum.clone());
  17966. this.vectors[2].x = this.maximum.x;
  17967. this.vectors.push(this.minimum.clone());
  17968. this.vectors[3].y = this.maximum.y;
  17969. this.vectors.push(this.minimum.clone());
  17970. this.vectors[4].z = this.maximum.z;
  17971. this.vectors.push(this.maximum.clone());
  17972. this.vectors[5].z = this.minimum.z;
  17973. this.vectors.push(this.maximum.clone());
  17974. this.vectors[6].x = this.minimum.x;
  17975. this.vectors.push(this.maximum.clone());
  17976. this.vectors[7].y = this.minimum.y;
  17977. // OBB
  17978. this.center = this.maximum.add(this.minimum).scale(0.5);
  17979. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17980. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17981. // World
  17982. for (var index = 0; index < this.vectors.length; index++) {
  17983. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17984. }
  17985. this.minimumWorld = BABYLON.Vector3.Zero();
  17986. this.maximumWorld = BABYLON.Vector3.Zero();
  17987. this.centerWorld = BABYLON.Vector3.Zero();
  17988. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17989. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17990. };
  17991. /**
  17992. * Scale the current bounding box by applying a scale factor
  17993. * @param factor defines the scale factor to apply
  17994. * @returns the current bounding box
  17995. */
  17996. BoundingBox.prototype.scale = function (factor) {
  17997. var diff = this.maximum.subtract(this.minimum);
  17998. var distance = diff.length() * factor;
  17999. diff.normalize();
  18000. var newRadius = diff.scale(distance / 2);
  18001. var min = this.center.subtract(newRadius);
  18002. var max = this.center.add(newRadius);
  18003. this.reConstruct(min, max);
  18004. return this;
  18005. };
  18006. BoundingBox.prototype.getWorldMatrix = function () {
  18007. return this._worldMatrix;
  18008. };
  18009. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18010. this._worldMatrix.copyFrom(matrix);
  18011. return this;
  18012. };
  18013. BoundingBox.prototype._update = function (world) {
  18014. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18015. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18016. for (var index = 0; index < this.vectors.length; index++) {
  18017. var v = this.vectorsWorld[index];
  18018. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18019. if (v.x < this.minimumWorld.x)
  18020. this.minimumWorld.x = v.x;
  18021. if (v.y < this.minimumWorld.y)
  18022. this.minimumWorld.y = v.y;
  18023. if (v.z < this.minimumWorld.z)
  18024. this.minimumWorld.z = v.z;
  18025. if (v.x > this.maximumWorld.x)
  18026. this.maximumWorld.x = v.x;
  18027. if (v.y > this.maximumWorld.y)
  18028. this.maximumWorld.y = v.y;
  18029. if (v.z > this.maximumWorld.z)
  18030. this.maximumWorld.z = v.z;
  18031. }
  18032. // Extend
  18033. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18034. this.extendSizeWorld.scaleInPlace(0.5);
  18035. // OBB
  18036. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18037. this.centerWorld.scaleInPlace(0.5);
  18038. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18039. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18040. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18041. this._worldMatrix = world;
  18042. };
  18043. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18044. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18045. };
  18046. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18047. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18048. };
  18049. BoundingBox.prototype.intersectsPoint = function (point) {
  18050. var delta = -BABYLON.Epsilon;
  18051. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18052. return false;
  18053. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18054. return false;
  18055. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18056. return false;
  18057. return true;
  18058. };
  18059. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18060. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18061. };
  18062. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18063. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18064. return false;
  18065. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18066. return false;
  18067. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18068. return false;
  18069. return true;
  18070. };
  18071. // Statics
  18072. BoundingBox.Intersects = function (box0, box1) {
  18073. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18074. return false;
  18075. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18076. return false;
  18077. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18078. return false;
  18079. return true;
  18080. };
  18081. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18082. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18083. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18084. return (num <= (sphereRadius * sphereRadius));
  18085. };
  18086. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18087. for (var p = 0; p < 6; p++) {
  18088. for (var i = 0; i < 8; i++) {
  18089. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18090. return false;
  18091. }
  18092. }
  18093. }
  18094. return true;
  18095. };
  18096. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18097. for (var p = 0; p < 6; p++) {
  18098. var inCount = 8;
  18099. for (var i = 0; i < 8; i++) {
  18100. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18101. --inCount;
  18102. }
  18103. else {
  18104. break;
  18105. }
  18106. }
  18107. if (inCount === 0)
  18108. return false;
  18109. }
  18110. return true;
  18111. };
  18112. return BoundingBox;
  18113. }());
  18114. BABYLON.BoundingBox = BoundingBox;
  18115. })(BABYLON || (BABYLON = {}));
  18116. //# sourceMappingURL=babylon.boundingBox.js.map
  18117. var BABYLON;
  18118. (function (BABYLON) {
  18119. var computeBoxExtents = function (axis, box) {
  18120. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18121. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18122. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18123. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18124. var r = r0 + r1 + r2;
  18125. return {
  18126. min: p - r,
  18127. max: p + r
  18128. };
  18129. };
  18130. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18131. var axisOverlap = function (axis, box0, box1) {
  18132. var result0 = computeBoxExtents(axis, box0);
  18133. var result1 = computeBoxExtents(axis, box1);
  18134. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18135. };
  18136. var BoundingInfo = /** @class */ (function () {
  18137. function BoundingInfo(minimum, maximum) {
  18138. this.minimum = minimum;
  18139. this.maximum = maximum;
  18140. this._isLocked = false;
  18141. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18142. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18143. }
  18144. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18145. get: function () {
  18146. return this._isLocked;
  18147. },
  18148. set: function (value) {
  18149. this._isLocked = value;
  18150. },
  18151. enumerable: true,
  18152. configurable: true
  18153. });
  18154. // Methods
  18155. BoundingInfo.prototype.update = function (world) {
  18156. if (this._isLocked) {
  18157. return;
  18158. }
  18159. this.boundingBox._update(world);
  18160. this.boundingSphere._update(world);
  18161. };
  18162. /**
  18163. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18164. * @param center New center of the bounding info
  18165. * @param extend New extend of the bounding info
  18166. */
  18167. BoundingInfo.prototype.centerOn = function (center, extend) {
  18168. this.minimum = center.subtract(extend);
  18169. this.maximum = center.add(extend);
  18170. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18171. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18172. return this;
  18173. };
  18174. /**
  18175. * Scale the current bounding info by applying a scale factor
  18176. * @param factor defines the scale factor to apply
  18177. * @returns the current bounding info
  18178. */
  18179. BoundingInfo.prototype.scale = function (factor) {
  18180. this.boundingBox.scale(factor);
  18181. this.boundingSphere.scale(factor);
  18182. return this;
  18183. };
  18184. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18185. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18186. return false;
  18187. return this.boundingBox.isInFrustum(frustumPlanes);
  18188. };
  18189. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18190. /**
  18191. * Gets the world distance between the min and max points of the bounding box
  18192. */
  18193. get: function () {
  18194. var boundingBox = this.boundingBox;
  18195. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18196. return size.length();
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18202. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18203. };
  18204. BoundingInfo.prototype._checkCollision = function (collider) {
  18205. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18206. };
  18207. BoundingInfo.prototype.intersectsPoint = function (point) {
  18208. if (!this.boundingSphere.centerWorld) {
  18209. return false;
  18210. }
  18211. if (!this.boundingSphere.intersectsPoint(point)) {
  18212. return false;
  18213. }
  18214. if (!this.boundingBox.intersectsPoint(point)) {
  18215. return false;
  18216. }
  18217. return true;
  18218. };
  18219. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18220. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18221. return false;
  18222. }
  18223. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18224. return false;
  18225. }
  18226. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18227. return false;
  18228. }
  18229. if (!precise) {
  18230. return true;
  18231. }
  18232. var box0 = this.boundingBox;
  18233. var box1 = boundingInfo.boundingBox;
  18234. if (!axisOverlap(box0.directions[0], box0, box1))
  18235. return false;
  18236. if (!axisOverlap(box0.directions[1], box0, box1))
  18237. return false;
  18238. if (!axisOverlap(box0.directions[2], box0, box1))
  18239. return false;
  18240. if (!axisOverlap(box1.directions[0], box0, box1))
  18241. return false;
  18242. if (!axisOverlap(box1.directions[1], box0, box1))
  18243. return false;
  18244. if (!axisOverlap(box1.directions[2], box0, box1))
  18245. return false;
  18246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18247. return false;
  18248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18249. return false;
  18250. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18251. return false;
  18252. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18253. return false;
  18254. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18255. return false;
  18256. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18257. return false;
  18258. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18259. return false;
  18260. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18261. return false;
  18262. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18263. return false;
  18264. return true;
  18265. };
  18266. return BoundingInfo;
  18267. }());
  18268. BABYLON.BoundingInfo = BoundingInfo;
  18269. })(BABYLON || (BABYLON = {}));
  18270. //# sourceMappingURL=babylon.boundingInfo.js.map
  18271. var BABYLON;
  18272. (function (BABYLON) {
  18273. var TransformNode = /** @class */ (function (_super) {
  18274. __extends(TransformNode, _super);
  18275. function TransformNode(name, scene, isPure) {
  18276. if (scene === void 0) { scene = null; }
  18277. if (isPure === void 0) { isPure = true; }
  18278. var _this = _super.call(this, name, scene) || this;
  18279. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18280. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18281. _this._up = new BABYLON.Vector3(0, 1, 0);
  18282. _this._right = new BABYLON.Vector3(1, 0, 0);
  18283. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18284. // Properties
  18285. _this._rotation = BABYLON.Vector3.Zero();
  18286. _this._scaling = BABYLON.Vector3.One();
  18287. _this._isDirty = false;
  18288. /**
  18289. * Set the billboard mode. Default is 0.
  18290. *
  18291. * | Value | Type | Description |
  18292. * | --- | --- | --- |
  18293. * | 0 | BILLBOARDMODE_NONE | |
  18294. * | 1 | BILLBOARDMODE_X | |
  18295. * | 2 | BILLBOARDMODE_Y | |
  18296. * | 4 | BILLBOARDMODE_Z | |
  18297. * | 7 | BILLBOARDMODE_ALL | |
  18298. *
  18299. */
  18300. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18301. _this.scalingDeterminant = 1;
  18302. _this.infiniteDistance = false;
  18303. /**
  18304. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18305. * By default the system will update normals to compensate
  18306. */
  18307. _this.ignoreNonUniformScaling = false;
  18308. _this.position = BABYLON.Vector3.Zero();
  18309. _this._localWorld = BABYLON.Matrix.Zero();
  18310. _this._worldMatrix = BABYLON.Matrix.Zero();
  18311. _this._worldMatrixDeterminant = 0;
  18312. _this._absolutePosition = BABYLON.Vector3.Zero();
  18313. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18314. _this._postMultiplyPivotMatrix = false;
  18315. _this._isWorldMatrixFrozen = false;
  18316. /**
  18317. * An event triggered after the world matrix is updated
  18318. */
  18319. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18320. _this._nonUniformScaling = false;
  18321. if (isPure) {
  18322. _this.getScene().addTransformNode(_this);
  18323. }
  18324. return _this;
  18325. }
  18326. /**
  18327. * Gets a string idenfifying the name of the class
  18328. * @returns "TransformNode" string
  18329. */
  18330. TransformNode.prototype.getClassName = function () {
  18331. return "TransformNode";
  18332. };
  18333. Object.defineProperty(TransformNode.prototype, "rotation", {
  18334. /**
  18335. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18336. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18337. * Default : (0.0, 0.0, 0.0)
  18338. */
  18339. get: function () {
  18340. return this._rotation;
  18341. },
  18342. set: function (newRotation) {
  18343. this._rotation = newRotation;
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(TransformNode.prototype, "scaling", {
  18349. /**
  18350. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18351. * Default : (1.0, 1.0, 1.0)
  18352. */
  18353. get: function () {
  18354. return this._scaling;
  18355. },
  18356. /**
  18357. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18358. * Default : (1.0, 1.0, 1.0)
  18359. */
  18360. set: function (newScaling) {
  18361. this._scaling = newScaling;
  18362. },
  18363. enumerable: true,
  18364. configurable: true
  18365. });
  18366. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18367. /**
  18368. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18369. * It's null by default.
  18370. * 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)
  18371. */
  18372. get: function () {
  18373. return this._rotationQuaternion;
  18374. },
  18375. set: function (quaternion) {
  18376. this._rotationQuaternion = quaternion;
  18377. //reset the rotation vector.
  18378. if (quaternion && this.rotation.length()) {
  18379. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18380. }
  18381. },
  18382. enumerable: true,
  18383. configurable: true
  18384. });
  18385. Object.defineProperty(TransformNode.prototype, "forward", {
  18386. /**
  18387. * The forward direction of that transform in world space.
  18388. */
  18389. get: function () {
  18390. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. Object.defineProperty(TransformNode.prototype, "up", {
  18396. /**
  18397. * The up direction of that transform in world space.
  18398. */
  18399. get: function () {
  18400. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. Object.defineProperty(TransformNode.prototype, "right", {
  18406. /**
  18407. * The right direction of that transform in world space.
  18408. */
  18409. get: function () {
  18410. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18411. },
  18412. enumerable: true,
  18413. configurable: true
  18414. });
  18415. /**
  18416. * Returns the latest update of the World matrix
  18417. * Returns a Matrix.
  18418. */
  18419. TransformNode.prototype.getWorldMatrix = function () {
  18420. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18421. this.computeWorldMatrix();
  18422. }
  18423. return this._worldMatrix;
  18424. };
  18425. /** @hidden */
  18426. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18427. return this._worldMatrixDeterminant;
  18428. };
  18429. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18430. /**
  18431. * Returns directly the latest state of the mesh World matrix.
  18432. * A Matrix is returned.
  18433. */
  18434. get: function () {
  18435. return this._worldMatrix;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. /**
  18441. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18442. * Returns the TransformNode.
  18443. */
  18444. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18445. this._poseMatrix.copyFrom(matrix);
  18446. return this;
  18447. };
  18448. /**
  18449. * Returns the mesh Pose matrix.
  18450. * Returned object : Matrix
  18451. */
  18452. TransformNode.prototype.getPoseMatrix = function () {
  18453. return this._poseMatrix;
  18454. };
  18455. TransformNode.prototype._isSynchronized = function () {
  18456. if (this._isDirty) {
  18457. return false;
  18458. }
  18459. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18460. return false;
  18461. if (this._cache.pivotMatrixUpdated) {
  18462. return false;
  18463. }
  18464. if (this.infiniteDistance) {
  18465. return false;
  18466. }
  18467. if (!this._cache.position.equals(this.position))
  18468. return false;
  18469. if (this.rotationQuaternion) {
  18470. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18471. return false;
  18472. }
  18473. if (!this._cache.rotation.equals(this.rotation))
  18474. return false;
  18475. if (!this._cache.scaling.equals(this.scaling))
  18476. return false;
  18477. return true;
  18478. };
  18479. TransformNode.prototype._initCache = function () {
  18480. _super.prototype._initCache.call(this);
  18481. this._cache.localMatrixUpdated = false;
  18482. this._cache.position = BABYLON.Vector3.Zero();
  18483. this._cache.scaling = BABYLON.Vector3.Zero();
  18484. this._cache.rotation = BABYLON.Vector3.Zero();
  18485. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18486. this._cache.billboardMode = -1;
  18487. };
  18488. TransformNode.prototype.markAsDirty = function (property) {
  18489. if (property === "rotation") {
  18490. this.rotationQuaternion = null;
  18491. }
  18492. this._currentRenderId = Number.MAX_VALUE;
  18493. this._isDirty = true;
  18494. return this;
  18495. };
  18496. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18497. /**
  18498. * Returns the current mesh absolute position.
  18499. * Retuns a Vector3.
  18500. */
  18501. get: function () {
  18502. return this._absolutePosition;
  18503. },
  18504. enumerable: true,
  18505. configurable: true
  18506. });
  18507. /**
  18508. * Sets a new matrix to apply before all other transformation
  18509. * @param matrix defines the transform matrix
  18510. * @returns the current TransformNode
  18511. */
  18512. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18513. return this.setPivotMatrix(matrix, false);
  18514. };
  18515. /**
  18516. * Sets a new pivot matrix to the current node
  18517. * @param matrix defines the new pivot matrix to use
  18518. * @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
  18519. * @returns the current TransformNode
  18520. */
  18521. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18522. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18523. this._pivotMatrix = matrix.clone();
  18524. this._cache.pivotMatrixUpdated = true;
  18525. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18526. if (this._postMultiplyPivotMatrix) {
  18527. if (!this._pivotMatrixInverse) {
  18528. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18529. }
  18530. else {
  18531. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18532. }
  18533. }
  18534. return this;
  18535. };
  18536. /**
  18537. * Returns the mesh pivot matrix.
  18538. * Default : Identity.
  18539. * A Matrix is returned.
  18540. */
  18541. TransformNode.prototype.getPivotMatrix = function () {
  18542. return this._pivotMatrix;
  18543. };
  18544. /**
  18545. * Prevents the World matrix to be computed any longer.
  18546. * Returns the TransformNode.
  18547. */
  18548. TransformNode.prototype.freezeWorldMatrix = function () {
  18549. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18550. this.computeWorldMatrix(true);
  18551. this._isWorldMatrixFrozen = true;
  18552. return this;
  18553. };
  18554. /**
  18555. * Allows back the World matrix computation.
  18556. * Returns the TransformNode.
  18557. */
  18558. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18559. this._isWorldMatrixFrozen = false;
  18560. this.computeWorldMatrix(true);
  18561. return this;
  18562. };
  18563. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18564. /**
  18565. * True if the World matrix has been frozen.
  18566. * Returns a boolean.
  18567. */
  18568. get: function () {
  18569. return this._isWorldMatrixFrozen;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. /**
  18575. * Retuns the mesh absolute position in the World.
  18576. * Returns a Vector3.
  18577. */
  18578. TransformNode.prototype.getAbsolutePosition = function () {
  18579. this.computeWorldMatrix();
  18580. return this._absolutePosition;
  18581. };
  18582. /**
  18583. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18584. * Returns the TransformNode.
  18585. */
  18586. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18587. if (!absolutePosition) {
  18588. return this;
  18589. }
  18590. var absolutePositionX;
  18591. var absolutePositionY;
  18592. var absolutePositionZ;
  18593. if (absolutePosition.x === undefined) {
  18594. if (arguments.length < 3) {
  18595. return this;
  18596. }
  18597. absolutePositionX = arguments[0];
  18598. absolutePositionY = arguments[1];
  18599. absolutePositionZ = arguments[2];
  18600. }
  18601. else {
  18602. absolutePositionX = absolutePosition.x;
  18603. absolutePositionY = absolutePosition.y;
  18604. absolutePositionZ = absolutePosition.z;
  18605. }
  18606. if (this.parent) {
  18607. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18608. invertParentWorldMatrix.invert();
  18609. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18610. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18611. }
  18612. else {
  18613. this.position.x = absolutePositionX;
  18614. this.position.y = absolutePositionY;
  18615. this.position.z = absolutePositionZ;
  18616. }
  18617. return this;
  18618. };
  18619. /**
  18620. * Sets the mesh position in its local space.
  18621. * Returns the TransformNode.
  18622. */
  18623. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18624. this.computeWorldMatrix();
  18625. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18626. return this;
  18627. };
  18628. /**
  18629. * Returns the mesh position in the local space from the current World matrix values.
  18630. * Returns a new Vector3.
  18631. */
  18632. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18633. this.computeWorldMatrix();
  18634. var invLocalWorldMatrix = this._localWorld.clone();
  18635. invLocalWorldMatrix.invert();
  18636. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18637. };
  18638. /**
  18639. * Translates the mesh along the passed Vector3 in its local space.
  18640. * Returns the TransformNode.
  18641. */
  18642. TransformNode.prototype.locallyTranslate = function (vector3) {
  18643. this.computeWorldMatrix(true);
  18644. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18645. return this;
  18646. };
  18647. /**
  18648. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18649. * @param targetPoint the position (must be in same space as current mesh) to look at
  18650. * @param yawCor optional yaw (y-axis) correction in radians
  18651. * @param pitchCor optional pitch (x-axis) correction in radians
  18652. * @param rollCor optional roll (z-axis) correction in radians
  18653. * @param space the choosen space of the target
  18654. * @returns the TransformNode.
  18655. */
  18656. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18657. if (yawCor === void 0) { yawCor = 0; }
  18658. if (pitchCor === void 0) { pitchCor = 0; }
  18659. if (rollCor === void 0) { rollCor = 0; }
  18660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18661. var dv = TransformNode._lookAtVectorCache;
  18662. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18663. targetPoint.subtractToRef(pos, dv);
  18664. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18665. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18666. var pitch = Math.atan2(dv.y, len);
  18667. if (this.rotationQuaternion) {
  18668. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18669. }
  18670. else {
  18671. this.rotation.x = pitch + pitchCor;
  18672. this.rotation.y = yaw + yawCor;
  18673. this.rotation.z = rollCor;
  18674. }
  18675. return this;
  18676. };
  18677. /**
  18678. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18679. * This Vector3 is expressed in the World space.
  18680. */
  18681. TransformNode.prototype.getDirection = function (localAxis) {
  18682. var result = BABYLON.Vector3.Zero();
  18683. this.getDirectionToRef(localAxis, result);
  18684. return result;
  18685. };
  18686. /**
  18687. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18688. * localAxis is expressed in the mesh local space.
  18689. * result is computed in the Wordl space from the mesh World matrix.
  18690. * Returns the TransformNode.
  18691. */
  18692. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18693. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18694. return this;
  18695. };
  18696. /**
  18697. * Sets a new pivot point to the current node
  18698. * @param point defines the new pivot point to use
  18699. * @param space defines if the point is in world or local space (local by default)
  18700. * @returns the current TransformNode
  18701. */
  18702. TransformNode.prototype.setPivotPoint = function (point, space) {
  18703. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18704. if (this.getScene().getRenderId() == 0) {
  18705. this.computeWorldMatrix(true);
  18706. }
  18707. var wm = this.getWorldMatrix();
  18708. if (space == BABYLON.Space.WORLD) {
  18709. var tmat = BABYLON.Tmp.Matrix[0];
  18710. wm.invertToRef(tmat);
  18711. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18712. }
  18713. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18714. };
  18715. /**
  18716. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18717. */
  18718. TransformNode.prototype.getPivotPoint = function () {
  18719. var point = BABYLON.Vector3.Zero();
  18720. this.getPivotPointToRef(point);
  18721. return point;
  18722. };
  18723. /**
  18724. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.getPivotPointToRef = function (result) {
  18728. result.x = -this._pivotMatrix.m[12];
  18729. result.y = -this._pivotMatrix.m[13];
  18730. result.z = -this._pivotMatrix.m[14];
  18731. return this;
  18732. };
  18733. /**
  18734. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18735. */
  18736. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18737. var point = BABYLON.Vector3.Zero();
  18738. this.getAbsolutePivotPointToRef(point);
  18739. return point;
  18740. };
  18741. /**
  18742. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18743. * Returns the TransformNode.
  18744. */
  18745. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18746. result.x = this._pivotMatrix.m[12];
  18747. result.y = this._pivotMatrix.m[13];
  18748. result.z = this._pivotMatrix.m[14];
  18749. this.getPivotPointToRef(result);
  18750. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18751. return this;
  18752. };
  18753. /**
  18754. * Defines the passed node as the parent of the current node.
  18755. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18756. * Returns the TransformNode.
  18757. */
  18758. TransformNode.prototype.setParent = function (node) {
  18759. if (!node && !this.parent) {
  18760. return this;
  18761. }
  18762. if (!node) {
  18763. var rotation = BABYLON.Tmp.Quaternion[0];
  18764. var position = BABYLON.Tmp.Vector3[0];
  18765. var scale = BABYLON.Tmp.Vector3[1];
  18766. if (this.parent && this.parent.computeWorldMatrix) {
  18767. this.parent.computeWorldMatrix(true);
  18768. }
  18769. this.computeWorldMatrix(true);
  18770. this.getWorldMatrix().decompose(scale, rotation, position);
  18771. if (this.rotationQuaternion) {
  18772. this.rotationQuaternion.copyFrom(rotation);
  18773. }
  18774. else {
  18775. rotation.toEulerAnglesToRef(this.rotation);
  18776. }
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. this.position.x = position.x;
  18781. this.position.y = position.y;
  18782. this.position.z = position.z;
  18783. }
  18784. else {
  18785. var rotation = BABYLON.Tmp.Quaternion[0];
  18786. var position = BABYLON.Tmp.Vector3[0];
  18787. var scale = BABYLON.Tmp.Vector3[1];
  18788. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18789. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18790. this.computeWorldMatrix(true);
  18791. node.computeWorldMatrix(true);
  18792. node.getWorldMatrix().invertToRef(invParentMatrix);
  18793. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18794. diffMatrix.decompose(scale, rotation, position);
  18795. if (this.rotationQuaternion) {
  18796. this.rotationQuaternion.copyFrom(rotation);
  18797. }
  18798. else {
  18799. rotation.toEulerAnglesToRef(this.rotation);
  18800. }
  18801. this.position.x = position.x;
  18802. this.position.y = position.y;
  18803. this.position.z = position.z;
  18804. this.scaling.x = scale.x;
  18805. this.scaling.y = scale.y;
  18806. this.scaling.z = scale.z;
  18807. }
  18808. this.parent = node;
  18809. return this;
  18810. };
  18811. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18812. get: function () {
  18813. return this._nonUniformScaling;
  18814. },
  18815. enumerable: true,
  18816. configurable: true
  18817. });
  18818. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18819. if (this._nonUniformScaling === value) {
  18820. return false;
  18821. }
  18822. this._nonUniformScaling = value;
  18823. return true;
  18824. };
  18825. /**
  18826. * Attach the current TransformNode to another TransformNode associated with a bone
  18827. * @param bone Bone affecting the TransformNode
  18828. * @param affectedTransformNode TransformNode associated with the bone
  18829. */
  18830. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18831. this._transformToBoneReferal = affectedTransformNode;
  18832. this.parent = bone;
  18833. if (bone.getWorldMatrix().determinant() < 0) {
  18834. this.scalingDeterminant *= -1;
  18835. }
  18836. return this;
  18837. };
  18838. TransformNode.prototype.detachFromBone = function () {
  18839. if (!this.parent) {
  18840. return this;
  18841. }
  18842. if (this.parent.getWorldMatrix().determinant() < 0) {
  18843. this.scalingDeterminant *= -1;
  18844. }
  18845. this._transformToBoneReferal = null;
  18846. this.parent = null;
  18847. return this;
  18848. };
  18849. /**
  18850. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18851. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18852. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18853. * The passed axis is also normalized.
  18854. * Returns the TransformNode.
  18855. */
  18856. TransformNode.prototype.rotate = function (axis, amount, space) {
  18857. axis.normalize();
  18858. if (!this.rotationQuaternion) {
  18859. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18860. this.rotation = BABYLON.Vector3.Zero();
  18861. }
  18862. var rotationQuaternion;
  18863. if (!space || space === BABYLON.Space.LOCAL) {
  18864. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18865. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18866. }
  18867. else {
  18868. if (this.parent) {
  18869. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18870. invertParentWorldMatrix.invert();
  18871. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18872. }
  18873. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18874. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18875. }
  18876. return this;
  18877. };
  18878. /**
  18879. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18880. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18881. * The passed axis is also normalized.
  18882. * Returns the TransformNode.
  18883. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18884. */
  18885. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18886. axis.normalize();
  18887. if (!this.rotationQuaternion) {
  18888. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18889. this.rotation.copyFromFloats(0, 0, 0);
  18890. }
  18891. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18892. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18893. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18894. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18895. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18896. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18897. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18898. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18899. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18900. return this;
  18901. };
  18902. /**
  18903. * Translates the mesh along the axis vector for the passed distance in the given space.
  18904. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18905. * Returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.translate = function (axis, distance, space) {
  18908. var displacementVector = axis.scale(distance);
  18909. if (!space || space === BABYLON.Space.LOCAL) {
  18910. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18911. this.setPositionWithLocalVector(tempV3);
  18912. }
  18913. else {
  18914. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18915. }
  18916. return this;
  18917. };
  18918. /**
  18919. * Adds a rotation step to the mesh current rotation.
  18920. * x, y, z are Euler angles expressed in radians.
  18921. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18922. * This means this rotation is made in the mesh local space only.
  18923. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18924. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18925. * ```javascript
  18926. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18927. * ```
  18928. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18929. * 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.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.addRotation = function (x, y, z) {
  18933. var rotationQuaternion;
  18934. if (this.rotationQuaternion) {
  18935. rotationQuaternion = this.rotationQuaternion;
  18936. }
  18937. else {
  18938. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18939. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18940. }
  18941. var accumulation = BABYLON.Tmp.Quaternion[0];
  18942. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18943. rotationQuaternion.multiplyInPlace(accumulation);
  18944. if (!this.rotationQuaternion) {
  18945. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18946. }
  18947. return this;
  18948. };
  18949. /**
  18950. * Computes the mesh World matrix and returns it.
  18951. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18952. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18953. * If the parameter `force`is set to `true`, the actual computation is done.
  18954. * Returns the mesh World Matrix.
  18955. */
  18956. TransformNode.prototype.computeWorldMatrix = function (force) {
  18957. if (this._isWorldMatrixFrozen) {
  18958. return this._worldMatrix;
  18959. }
  18960. if (!force && this.isSynchronized(true)) {
  18961. this._currentRenderId = this.getScene().getRenderId();
  18962. return this._worldMatrix;
  18963. }
  18964. this._cache.position.copyFrom(this.position);
  18965. this._cache.scaling.copyFrom(this.scaling);
  18966. this._cache.pivotMatrixUpdated = false;
  18967. this._cache.billboardMode = this.billboardMode;
  18968. this._currentRenderId = this.getScene().getRenderId();
  18969. this._childRenderId = this.getScene().getRenderId();
  18970. this._isDirty = false;
  18971. // Scaling
  18972. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18973. // Rotation
  18974. //rotate, if quaternion is set and rotation was used
  18975. if (this.rotationQuaternion) {
  18976. var len = this.rotation.length();
  18977. if (len) {
  18978. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18979. this.rotation.copyFromFloats(0, 0, 0);
  18980. }
  18981. }
  18982. if (this.rotationQuaternion) {
  18983. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18984. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18985. }
  18986. else {
  18987. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18988. this._cache.rotation.copyFrom(this.rotation);
  18989. }
  18990. // Translation
  18991. var camera = this.getScene().activeCamera;
  18992. if (this.infiniteDistance && !this.parent && camera) {
  18993. var cameraWorldMatrix = camera.getWorldMatrix();
  18994. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18995. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18996. }
  18997. else {
  18998. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18999. }
  19000. // Composing transformations
  19001. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19002. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19003. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19004. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19005. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19006. // Need to decompose each rotation here
  19007. var currentPosition = BABYLON.Tmp.Vector3[3];
  19008. if (this.parent && this.parent.getWorldMatrix) {
  19009. if (this._transformToBoneReferal) {
  19010. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19011. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19012. }
  19013. else {
  19014. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19015. }
  19016. }
  19017. else {
  19018. currentPosition.copyFrom(this.position);
  19019. }
  19020. currentPosition.subtractInPlace(camera.globalPosition);
  19021. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19022. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19023. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19024. }
  19025. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19026. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19027. }
  19028. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19029. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19030. }
  19031. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. else {
  19034. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19035. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19036. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19037. }
  19038. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19039. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19040. }
  19041. // Post multiply inverse of pivotMatrix
  19042. if (this._postMultiplyPivotMatrix) {
  19043. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19044. }
  19045. // Local world
  19046. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19047. // Parent
  19048. if (this.parent && this.parent.getWorldMatrix) {
  19049. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19050. if (this._transformToBoneReferal) {
  19051. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19052. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19053. }
  19054. else {
  19055. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19056. }
  19057. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19058. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19059. this._worldMatrix.copyFrom(this._localWorld);
  19060. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19061. }
  19062. else {
  19063. if (this._transformToBoneReferal) {
  19064. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19065. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19066. }
  19067. else {
  19068. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19069. }
  19070. }
  19071. this._markSyncedWithParent();
  19072. }
  19073. else {
  19074. this._worldMatrix.copyFrom(this._localWorld);
  19075. }
  19076. // Normal matrix
  19077. if (!this.ignoreNonUniformScaling) {
  19078. if (this.scaling.isNonUniform) {
  19079. this._updateNonUniformScalingState(true);
  19080. }
  19081. else if (this.parent && this.parent._nonUniformScaling) {
  19082. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19083. }
  19084. else {
  19085. this._updateNonUniformScalingState(false);
  19086. }
  19087. }
  19088. else {
  19089. this._updateNonUniformScalingState(false);
  19090. }
  19091. this._afterComputeWorldMatrix();
  19092. // Absolute position
  19093. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19094. // Callbacks
  19095. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19096. if (!this._poseMatrix) {
  19097. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19098. }
  19099. // Cache the determinant
  19100. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19101. return this._worldMatrix;
  19102. };
  19103. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19104. };
  19105. /**
  19106. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19107. * @param func: callback function to add
  19108. *
  19109. * Returns the TransformNode.
  19110. */
  19111. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19112. this.onAfterWorldMatrixUpdateObservable.add(func);
  19113. return this;
  19114. };
  19115. /**
  19116. * Removes a registered callback function.
  19117. * Returns the TransformNode.
  19118. */
  19119. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19120. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19121. return this;
  19122. };
  19123. /**
  19124. * Clone the current transform node
  19125. * Returns the new transform node
  19126. * @param name Name of the new clone
  19127. * @param newParent New parent for the clone
  19128. * @param doNotCloneChildren Do not clone children hierarchy
  19129. */
  19130. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19131. var _this = this;
  19132. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19133. result.name = name;
  19134. result.id = name;
  19135. if (newParent) {
  19136. result.parent = newParent;
  19137. }
  19138. if (!doNotCloneChildren) {
  19139. // Children
  19140. var directDescendants = this.getDescendants(true);
  19141. for (var index = 0; index < directDescendants.length; index++) {
  19142. var child = directDescendants[index];
  19143. if (child.clone) {
  19144. child.clone(name + "." + child.name, result);
  19145. }
  19146. }
  19147. }
  19148. return result;
  19149. };
  19150. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19151. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19152. serializationObject.type = this.getClassName();
  19153. // Parent
  19154. if (this.parent) {
  19155. serializationObject.parentId = this.parent.id;
  19156. }
  19157. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19158. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19159. }
  19160. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19161. serializationObject.isEnabled = this.isEnabled();
  19162. // Parent
  19163. if (this.parent) {
  19164. serializationObject.parentId = this.parent.id;
  19165. }
  19166. return serializationObject;
  19167. };
  19168. // Statics
  19169. /**
  19170. * Returns a new TransformNode object parsed from the source provided.
  19171. * The parameter `parsedMesh` is the source.
  19172. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19173. */
  19174. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19175. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19176. if (BABYLON.Tags) {
  19177. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19178. }
  19179. if (parsedTransformNode.localMatrix) {
  19180. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19181. }
  19182. else if (parsedTransformNode.pivotMatrix) {
  19183. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19184. }
  19185. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19186. // Parent
  19187. if (parsedTransformNode.parentId) {
  19188. transformNode._waitingParentId = parsedTransformNode.parentId;
  19189. }
  19190. return transformNode;
  19191. };
  19192. /**
  19193. * Releases resources associated with this transform node.
  19194. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19195. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19196. */
  19197. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19198. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19199. // Animations
  19200. this.getScene().stopAnimation(this);
  19201. // Remove from scene
  19202. this.getScene().removeTransformNode(this);
  19203. this.onAfterWorldMatrixUpdateObservable.clear();
  19204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19205. };
  19206. // Statics
  19207. TransformNode.BILLBOARDMODE_NONE = 0;
  19208. TransformNode.BILLBOARDMODE_X = 1;
  19209. TransformNode.BILLBOARDMODE_Y = 2;
  19210. TransformNode.BILLBOARDMODE_Z = 4;
  19211. TransformNode.BILLBOARDMODE_ALL = 7;
  19212. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19213. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19214. __decorate([
  19215. BABYLON.serializeAsVector3()
  19216. ], TransformNode.prototype, "_rotation", void 0);
  19217. __decorate([
  19218. BABYLON.serializeAsQuaternion()
  19219. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19220. __decorate([
  19221. BABYLON.serializeAsVector3()
  19222. ], TransformNode.prototype, "_scaling", void 0);
  19223. __decorate([
  19224. BABYLON.serialize()
  19225. ], TransformNode.prototype, "billboardMode", void 0);
  19226. __decorate([
  19227. BABYLON.serialize()
  19228. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19229. __decorate([
  19230. BABYLON.serialize()
  19231. ], TransformNode.prototype, "infiniteDistance", void 0);
  19232. __decorate([
  19233. BABYLON.serialize()
  19234. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19235. __decorate([
  19236. BABYLON.serializeAsVector3()
  19237. ], TransformNode.prototype, "position", void 0);
  19238. return TransformNode;
  19239. }(BABYLON.Node));
  19240. BABYLON.TransformNode = TransformNode;
  19241. })(BABYLON || (BABYLON = {}));
  19242. //# sourceMappingURL=babylon.transformNode.js.map
  19243. var BABYLON;
  19244. (function (BABYLON) {
  19245. /**
  19246. * Class used to store all common mesh properties
  19247. */
  19248. var AbstractMesh = /** @class */ (function (_super) {
  19249. __extends(AbstractMesh, _super);
  19250. // Constructor
  19251. /**
  19252. * Creates a new AbstractMesh
  19253. * @param name defines the name of the mesh
  19254. * @param scene defines the hosting scene
  19255. */
  19256. function AbstractMesh(name, scene) {
  19257. if (scene === void 0) { scene = null; }
  19258. var _this = _super.call(this, name, scene, false) || this;
  19259. _this._facetNb = 0; // facet number
  19260. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19261. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19262. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19263. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19264. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19265. _this._subDiv = {
  19266. max: 1,
  19267. X: 1,
  19268. Y: 1,
  19269. Z: 1
  19270. };
  19271. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19272. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19273. // Events
  19274. /**
  19275. * An event triggered when this mesh collides with another one
  19276. */
  19277. _this.onCollideObservable = new BABYLON.Observable();
  19278. /**
  19279. * An event triggered when the collision's position changes
  19280. */
  19281. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when material is changed
  19284. */
  19285. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19286. // Properties
  19287. /**
  19288. * Gets or sets the orientation for POV movement & rotation
  19289. */
  19290. _this.definedFacingForward = true;
  19291. /**
  19292. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19293. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19294. * * 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.
  19295. * @see http://doc.babylonjs.com/features/occlusionquery
  19296. */
  19297. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19298. /**
  19299. * 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:
  19300. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19301. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19302. * * 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.
  19303. * @see http://doc.babylonjs.com/features/occlusionquery
  19304. */
  19305. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19306. /**
  19307. * 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.
  19308. * The default value is -1 which means don't break the query and wait till the result
  19309. * @see http://doc.babylonjs.com/features/occlusionquery
  19310. */
  19311. _this.occlusionRetryCount = -1;
  19312. _this._occlusionInternalRetryCounter = 0;
  19313. _this._isOccluded = false;
  19314. _this._isOcclusionQueryInProgress = false;
  19315. _this._visibility = 1.0;
  19316. /** Gets or sets the alpha index used to sort transparent meshes
  19317. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19318. */
  19319. _this.alphaIndex = Number.MAX_VALUE;
  19320. /**
  19321. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19322. */
  19323. _this.isVisible = true;
  19324. /**
  19325. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19326. */
  19327. _this.isPickable = true;
  19328. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19329. _this.showSubMeshesBoundingBox = false;
  19330. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19331. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19332. */
  19333. _this.isBlocker = false;
  19334. /**
  19335. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19336. */
  19337. _this.enablePointerMoveEvents = false;
  19338. /**
  19339. * Specifies the rendering group id for this mesh (0 by default)
  19340. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19341. */
  19342. _this.renderingGroupId = 0;
  19343. _this._receiveShadows = false;
  19344. /**
  19345. * Gets or sets a boolean indicating if the outline must be rendered as well
  19346. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19347. */
  19348. _this.renderOutline = false;
  19349. /** Defines color to use when rendering outline */
  19350. _this.outlineColor = BABYLON.Color3.Red();
  19351. /** Define width to use when rendering outline */
  19352. _this.outlineWidth = 0.02;
  19353. /**
  19354. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19355. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19356. */
  19357. _this.renderOverlay = false;
  19358. /** Defines color to use when rendering overlay */
  19359. _this.overlayColor = BABYLON.Color3.Red();
  19360. /** Defines alpha to use when rendering overlay */
  19361. _this.overlayAlpha = 0.5;
  19362. _this._hasVertexAlpha = false;
  19363. _this._useVertexColors = true;
  19364. _this._computeBonesUsingShaders = true;
  19365. _this._numBoneInfluencers = 4;
  19366. _this._applyFog = true;
  19367. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19368. _this.useOctreeForRenderingSelection = true;
  19369. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19370. _this.useOctreeForPicking = true;
  19371. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19372. _this.useOctreeForCollisions = true;
  19373. _this._layerMask = 0x0FFFFFFF;
  19374. /**
  19375. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19376. */
  19377. _this.alwaysSelectAsActiveMesh = false;
  19378. /**
  19379. * Gets or sets the current action manager
  19380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19381. */
  19382. _this.actionManager = null;
  19383. /**
  19384. * Gets or sets impostor used for physic simulation
  19385. * @see http://doc.babylonjs.com/features/physics_engine
  19386. */
  19387. _this.physicsImpostor = null;
  19388. // Collisions
  19389. _this._checkCollisions = false;
  19390. _this._collisionMask = -1;
  19391. _this._collisionGroup = -1;
  19392. /**
  19393. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19394. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19395. */
  19396. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19397. /**
  19398. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19399. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19400. */
  19401. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19402. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19403. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19404. // Edges
  19405. /**
  19406. * Defines edge width used when edgesRenderer is enabled
  19407. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19408. */
  19409. _this.edgesWidth = 1;
  19410. /**
  19411. * Defines edge color used when edgesRenderer is enabled
  19412. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19413. */
  19414. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19415. // Cache
  19416. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19417. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19418. /** @hidden */
  19419. _this._renderId = 0;
  19420. /** @hidden */
  19421. _this._intersectionsInProgress = new Array();
  19422. /** @hidden */
  19423. _this._unIndexed = false;
  19424. /** @hidden */
  19425. _this._lightSources = new Array();
  19426. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19427. if (collidedMesh === void 0) { collidedMesh = null; }
  19428. //TODO move this to the collision coordinator!
  19429. if (_this.getScene().workerCollisions)
  19430. newPosition.multiplyInPlace(_this._collider._radius);
  19431. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19432. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19433. _this.position.addInPlace(_this._diffPositionForCollisions);
  19434. }
  19435. if (collidedMesh) {
  19436. _this.onCollideObservable.notifyObservers(collidedMesh);
  19437. }
  19438. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19439. };
  19440. _this.getScene().addMesh(_this);
  19441. _this._resyncLightSources();
  19442. return _this;
  19443. }
  19444. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19445. /**
  19446. * No billboard
  19447. */
  19448. get: function () {
  19449. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19450. },
  19451. enumerable: true,
  19452. configurable: true
  19453. });
  19454. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19455. /** Billboard on X axis */
  19456. get: function () {
  19457. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19463. /** Billboard on Y axis */
  19464. get: function () {
  19465. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19471. /** Billboard on Z axis */
  19472. get: function () {
  19473. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19479. /** Billboard on all axes */
  19480. get: function () {
  19481. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19487. /**
  19488. * Gets the number of facets in the mesh
  19489. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19490. */
  19491. get: function () {
  19492. return this._facetNb;
  19493. },
  19494. enumerable: true,
  19495. configurable: true
  19496. });
  19497. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19498. /**
  19499. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19500. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19501. */
  19502. get: function () {
  19503. return this._partitioningSubdivisions;
  19504. },
  19505. set: function (nb) {
  19506. this._partitioningSubdivisions = nb;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19512. /**
  19513. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19514. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19515. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19516. */
  19517. get: function () {
  19518. return this._partitioningBBoxRatio;
  19519. },
  19520. set: function (ratio) {
  19521. this._partitioningBBoxRatio = ratio;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19527. /**
  19528. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19529. * Works only for updatable meshes.
  19530. * Doesn't work with multi-materials
  19531. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19532. */
  19533. get: function () {
  19534. return this._facetDepthSort;
  19535. },
  19536. set: function (sort) {
  19537. this._facetDepthSort = sort;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19543. /**
  19544. * The location (Vector3) where the facet depth sort must be computed from.
  19545. * By default, the active camera position.
  19546. * Used only when facet depth sort is enabled
  19547. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19548. */
  19549. get: function () {
  19550. return this._facetDepthSortFrom;
  19551. },
  19552. set: function (location) {
  19553. this._facetDepthSortFrom = location;
  19554. },
  19555. enumerable: true,
  19556. configurable: true
  19557. });
  19558. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19559. /**
  19560. * gets a boolean indicating if facetData is enabled
  19561. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19562. */
  19563. get: function () {
  19564. return this._facetDataEnabled;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. /** @hidden */
  19570. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19571. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19572. return false;
  19573. }
  19574. this._markSubMeshesAsMiscDirty();
  19575. return true;
  19576. };
  19577. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19578. /** Set a function to call when this mesh collides with another one */
  19579. set: function (callback) {
  19580. if (this._onCollideObserver) {
  19581. this.onCollideObservable.remove(this._onCollideObserver);
  19582. }
  19583. this._onCollideObserver = this.onCollideObservable.add(callback);
  19584. },
  19585. enumerable: true,
  19586. configurable: true
  19587. });
  19588. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19589. /** Set a function to call when the collision's position changes */
  19590. set: function (callback) {
  19591. if (this._onCollisionPositionChangeObserver) {
  19592. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19593. }
  19594. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19600. /**
  19601. * 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
  19602. * @see http://doc.babylonjs.com/features/occlusionquery
  19603. */
  19604. get: function () {
  19605. return this._isOccluded;
  19606. },
  19607. set: function (value) {
  19608. this._isOccluded = value;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19614. /**
  19615. * Flag to check the progress status of the query
  19616. * @see http://doc.babylonjs.com/features/occlusionquery
  19617. */
  19618. get: function () {
  19619. return this._isOcclusionQueryInProgress;
  19620. },
  19621. enumerable: true,
  19622. configurable: true
  19623. });
  19624. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19625. /**
  19626. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19627. */
  19628. get: function () {
  19629. return this._visibility;
  19630. },
  19631. /**
  19632. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19633. */
  19634. set: function (value) {
  19635. if (this._visibility === value) {
  19636. return;
  19637. }
  19638. this._visibility = value;
  19639. this._markSubMeshesAsMiscDirty();
  19640. },
  19641. enumerable: true,
  19642. configurable: true
  19643. });
  19644. Object.defineProperty(AbstractMesh.prototype, "material", {
  19645. /** Gets or sets current material */
  19646. get: function () {
  19647. return this._material;
  19648. },
  19649. set: function (value) {
  19650. if (this._material === value) {
  19651. return;
  19652. }
  19653. this._material = value;
  19654. if (this.onMaterialChangedObservable.hasObservers) {
  19655. this.onMaterialChangedObservable.notifyObservers(this);
  19656. }
  19657. if (!this.subMeshes) {
  19658. return;
  19659. }
  19660. this._unBindEffect();
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19666. /**
  19667. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19668. * @see http://doc.babylonjs.com/babylon101/shadows
  19669. */
  19670. get: function () {
  19671. return this._receiveShadows;
  19672. },
  19673. set: function (value) {
  19674. if (this._receiveShadows === value) {
  19675. return;
  19676. }
  19677. this._receiveShadows = value;
  19678. this._markSubMeshesAsLightDirty();
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19684. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19685. get: function () {
  19686. return this._hasVertexAlpha;
  19687. },
  19688. set: function (value) {
  19689. if (this._hasVertexAlpha === value) {
  19690. return;
  19691. }
  19692. this._hasVertexAlpha = value;
  19693. this._markSubMeshesAsAttributesDirty();
  19694. this._markSubMeshesAsMiscDirty();
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19700. /** 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) */
  19701. get: function () {
  19702. return this._useVertexColors;
  19703. },
  19704. set: function (value) {
  19705. if (this._useVertexColors === value) {
  19706. return;
  19707. }
  19708. this._useVertexColors = value;
  19709. this._markSubMeshesAsAttributesDirty();
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19715. /**
  19716. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19717. */
  19718. get: function () {
  19719. return this._computeBonesUsingShaders;
  19720. },
  19721. set: function (value) {
  19722. if (this._computeBonesUsingShaders === value) {
  19723. return;
  19724. }
  19725. this._computeBonesUsingShaders = value;
  19726. this._markSubMeshesAsAttributesDirty();
  19727. },
  19728. enumerable: true,
  19729. configurable: true
  19730. });
  19731. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19732. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19733. get: function () {
  19734. return this._numBoneInfluencers;
  19735. },
  19736. set: function (value) {
  19737. if (this._numBoneInfluencers === value) {
  19738. return;
  19739. }
  19740. this._numBoneInfluencers = value;
  19741. this._markSubMeshesAsAttributesDirty();
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19747. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19748. get: function () {
  19749. return this._applyFog;
  19750. },
  19751. set: function (value) {
  19752. if (this._applyFog === value) {
  19753. return;
  19754. }
  19755. this._applyFog = value;
  19756. this._markSubMeshesAsMiscDirty();
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19762. /**
  19763. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19764. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19765. */
  19766. get: function () {
  19767. return this._layerMask;
  19768. },
  19769. set: function (value) {
  19770. if (value === this._layerMask) {
  19771. return;
  19772. }
  19773. this._layerMask = value;
  19774. this._resyncLightSources();
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19780. /**
  19781. * Gets or sets a collision mask used to mask collisions (default is -1).
  19782. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19783. */
  19784. get: function () {
  19785. return this._collisionMask;
  19786. },
  19787. set: function (mask) {
  19788. this._collisionMask = !isNaN(mask) ? mask : -1;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19794. /**
  19795. * Gets or sets the current collision group mask (-1 by default).
  19796. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19797. */
  19798. get: function () {
  19799. return this._collisionGroup;
  19800. },
  19801. set: function (mask) {
  19802. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19808. /** @hidden */
  19809. get: function () {
  19810. return null;
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19816. get: function () {
  19817. return this._skeleton;
  19818. },
  19819. /**
  19820. * Gets or sets a skeleton to apply skining transformations
  19821. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19822. */
  19823. set: function (value) {
  19824. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19825. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19826. }
  19827. if (value && value.needInitialSkinMatrix) {
  19828. value._registerMeshWithPoseMatrix(this);
  19829. }
  19830. this._skeleton = value;
  19831. if (!this._skeleton) {
  19832. this._bonesTransformMatrices = null;
  19833. }
  19834. this._markSubMeshesAsAttributesDirty();
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. /**
  19840. * Returns the string "AbstractMesh"
  19841. * @returns "AbstractMesh"
  19842. */
  19843. AbstractMesh.prototype.getClassName = function () {
  19844. return "AbstractMesh";
  19845. };
  19846. /**
  19847. * Gets a string representation of the current mesh
  19848. * @param fullDetails defines a boolean indicating if full details must be included
  19849. * @returns a string representation of the current mesh
  19850. */
  19851. AbstractMesh.prototype.toString = function (fullDetails) {
  19852. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19853. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19854. if (this._skeleton) {
  19855. ret += ", skeleton: " + this._skeleton.name;
  19856. }
  19857. if (fullDetails) {
  19858. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19859. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19860. }
  19861. return ret;
  19862. };
  19863. /** @hidden */
  19864. AbstractMesh.prototype._rebuild = function () {
  19865. if (this._occlusionQuery) {
  19866. this._occlusionQuery = null;
  19867. }
  19868. if (this._edgesRenderer) {
  19869. this._edgesRenderer._rebuild();
  19870. }
  19871. if (!this.subMeshes) {
  19872. return;
  19873. }
  19874. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19875. var subMesh = _a[_i];
  19876. subMesh._rebuild();
  19877. }
  19878. };
  19879. /** @hidden */
  19880. AbstractMesh.prototype._resyncLightSources = function () {
  19881. this._lightSources.length = 0;
  19882. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19883. var light = _a[_i];
  19884. if (!light.isEnabled()) {
  19885. continue;
  19886. }
  19887. if (light.canAffectMesh(this)) {
  19888. this._lightSources.push(light);
  19889. }
  19890. }
  19891. this._markSubMeshesAsLightDirty();
  19892. };
  19893. /** @hidden */
  19894. AbstractMesh.prototype._resyncLighSource = function (light) {
  19895. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19896. var index = this._lightSources.indexOf(light);
  19897. if (index === -1) {
  19898. if (!isIn) {
  19899. return;
  19900. }
  19901. this._lightSources.push(light);
  19902. }
  19903. else {
  19904. if (isIn) {
  19905. return;
  19906. }
  19907. this._lightSources.splice(index, 1);
  19908. }
  19909. this._markSubMeshesAsLightDirty();
  19910. };
  19911. /** @hidden */
  19912. AbstractMesh.prototype._unBindEffect = function () {
  19913. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19914. var subMesh = _a[_i];
  19915. subMesh.setEffect(null);
  19916. }
  19917. };
  19918. /** @hidden */
  19919. AbstractMesh.prototype._removeLightSource = function (light) {
  19920. var index = this._lightSources.indexOf(light);
  19921. if (index === -1) {
  19922. return;
  19923. }
  19924. this._lightSources.splice(index, 1);
  19925. this._markSubMeshesAsLightDirty();
  19926. };
  19927. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19928. if (!this.subMeshes) {
  19929. return;
  19930. }
  19931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19932. var subMesh = _a[_i];
  19933. if (subMesh._materialDefines) {
  19934. func(subMesh._materialDefines);
  19935. }
  19936. }
  19937. };
  19938. /** @hidden */
  19939. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19940. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19941. };
  19942. /** @hidden */
  19943. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19944. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19945. };
  19946. /** @hidden */
  19947. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19948. if (!this.subMeshes) {
  19949. return;
  19950. }
  19951. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19952. var subMesh = _a[_i];
  19953. var material = subMesh.getMaterial();
  19954. if (material) {
  19955. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19956. }
  19957. }
  19958. };
  19959. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19960. /**
  19961. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19962. */
  19963. get: function () {
  19964. return this._scaling;
  19965. },
  19966. set: function (newScaling) {
  19967. this._scaling = newScaling;
  19968. if (this.physicsImpostor) {
  19969. this.physicsImpostor.forceUpdate();
  19970. }
  19971. },
  19972. enumerable: true,
  19973. configurable: true
  19974. });
  19975. // Methods
  19976. /**
  19977. * Disables the mesh edge rendering mode
  19978. * @returns the currentAbstractMesh
  19979. */
  19980. AbstractMesh.prototype.disableEdgesRendering = function () {
  19981. if (this._edgesRenderer) {
  19982. this._edgesRenderer.dispose();
  19983. this._edgesRenderer = null;
  19984. }
  19985. return this;
  19986. };
  19987. /**
  19988. * Enables the edge rendering mode on the mesh.
  19989. * This mode makes the mesh edges visible
  19990. * @param epsilon defines the maximal distance between two angles to detect a face
  19991. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19992. * @returns the currentAbstractMesh
  19993. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19994. */
  19995. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19996. if (epsilon === void 0) { epsilon = 0.95; }
  19997. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19998. this.disableEdgesRendering();
  19999. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20000. return this;
  20001. };
  20002. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20003. /**
  20004. * Gets the edgesRenderer associated with the mesh
  20005. */
  20006. get: function () {
  20007. return this._edgesRenderer;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20013. /**
  20014. * Returns true if the mesh is blocked. Implemented by child classes
  20015. */
  20016. get: function () {
  20017. return false;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. /**
  20023. * Returns the mesh itself by default. Implemented by child classes
  20024. * @param camera defines the camera to use to pick the right LOD level
  20025. * @returns the currentAbstractMesh
  20026. */
  20027. AbstractMesh.prototype.getLOD = function (camera) {
  20028. return this;
  20029. };
  20030. /**
  20031. * Returns 0 by default. Implemented by child classes
  20032. * @returns an integer
  20033. */
  20034. AbstractMesh.prototype.getTotalVertices = function () {
  20035. return 0;
  20036. };
  20037. /**
  20038. * Returns null by default. Implemented by child classes
  20039. * @returns null
  20040. */
  20041. AbstractMesh.prototype.getIndices = function () {
  20042. return null;
  20043. };
  20044. /**
  20045. * Returns the array of the requested vertex data kind. Implemented by child classes
  20046. * @param kind defines the vertex data kind to use
  20047. * @returns null
  20048. */
  20049. AbstractMesh.prototype.getVerticesData = function (kind) {
  20050. return null;
  20051. };
  20052. /**
  20053. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20054. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20055. * Note that a new underlying VertexBuffer object is created each call.
  20056. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20057. * @param kind defines vertex data kind:
  20058. * * BABYLON.VertexBuffer.PositionKind
  20059. * * BABYLON.VertexBuffer.UVKind
  20060. * * BABYLON.VertexBuffer.UV2Kind
  20061. * * BABYLON.VertexBuffer.UV3Kind
  20062. * * BABYLON.VertexBuffer.UV4Kind
  20063. * * BABYLON.VertexBuffer.UV5Kind
  20064. * * BABYLON.VertexBuffer.UV6Kind
  20065. * * BABYLON.VertexBuffer.ColorKind
  20066. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20067. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20068. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20069. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20070. * @param data defines the data source
  20071. * @param updatable defines if the data must be flagged as updatable (or static)
  20072. * @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
  20073. * @returns the current mesh
  20074. */
  20075. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20076. return this;
  20077. };
  20078. /**
  20079. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20080. * If the mesh has no geometry, it is simply returned as it is.
  20081. * @param kind defines vertex data kind:
  20082. * * BABYLON.VertexBuffer.PositionKind
  20083. * * BABYLON.VertexBuffer.UVKind
  20084. * * BABYLON.VertexBuffer.UV2Kind
  20085. * * BABYLON.VertexBuffer.UV3Kind
  20086. * * BABYLON.VertexBuffer.UV4Kind
  20087. * * BABYLON.VertexBuffer.UV5Kind
  20088. * * BABYLON.VertexBuffer.UV6Kind
  20089. * * BABYLON.VertexBuffer.ColorKind
  20090. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20091. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20092. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20093. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20094. * @param data defines the data source
  20095. * @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
  20096. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20097. * @returns the current mesh
  20098. */
  20099. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20100. return this;
  20101. };
  20102. /**
  20103. * Sets the mesh indices,
  20104. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20105. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20106. * @param totalVertices Defines the total number of vertices
  20107. * @returns the current mesh
  20108. */
  20109. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20110. return this;
  20111. };
  20112. /**
  20113. * Gets a boolean indicating if specific vertex data is present
  20114. * @param kind defines the vertex data kind to use
  20115. * @returns true is data kind is present
  20116. */
  20117. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20118. return false;
  20119. };
  20120. /**
  20121. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20122. * @returns a BoundingInfo
  20123. */
  20124. AbstractMesh.prototype.getBoundingInfo = function () {
  20125. if (this._masterMesh) {
  20126. return this._masterMesh.getBoundingInfo();
  20127. }
  20128. if (!this._boundingInfo) {
  20129. // this._boundingInfo is being created here
  20130. this._updateBoundingInfo();
  20131. }
  20132. // cannot be null.
  20133. return this._boundingInfo;
  20134. };
  20135. /**
  20136. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20137. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20138. * @returns the current mesh
  20139. */
  20140. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20141. if (includeDescendants === void 0) { includeDescendants = true; }
  20142. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20143. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20144. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20145. if (maxDimension === 0) {
  20146. return this;
  20147. }
  20148. var scale = 1 / maxDimension;
  20149. this.scaling.scaleInPlace(scale);
  20150. return this;
  20151. };
  20152. /**
  20153. * Overwrite the current bounding info
  20154. * @param boundingInfo defines the new bounding info
  20155. * @returns the current mesh
  20156. */
  20157. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20158. this._boundingInfo = boundingInfo;
  20159. return this;
  20160. };
  20161. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20162. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20163. get: function () {
  20164. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. /** @hidden */
  20170. AbstractMesh.prototype._preActivate = function () {
  20171. };
  20172. /** @hidden */
  20173. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20174. };
  20175. /** @hidden */
  20176. AbstractMesh.prototype._activate = function (renderId) {
  20177. this._renderId = renderId;
  20178. };
  20179. /**
  20180. * Gets the current world matrix
  20181. * @returns a Matrix
  20182. */
  20183. AbstractMesh.prototype.getWorldMatrix = function () {
  20184. if (this._masterMesh) {
  20185. return this._masterMesh.getWorldMatrix();
  20186. }
  20187. return _super.prototype.getWorldMatrix.call(this);
  20188. };
  20189. /** @hidden */
  20190. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20191. if (this._masterMesh) {
  20192. return this._masterMesh._getWorldMatrixDeterminant();
  20193. }
  20194. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20195. };
  20196. // ================================== Point of View Movement =================================
  20197. /**
  20198. * Perform relative position change from the point of view of behind the front of the mesh.
  20199. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20200. * Supports definition of mesh facing forward or backward
  20201. * @param amountRight defines the distance on the right axis
  20202. * @param amountUp defines the distance on the up axis
  20203. * @param amountForward defines the distance on the forward axis
  20204. * @returns the current mesh
  20205. */
  20206. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20207. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20208. return this;
  20209. };
  20210. /**
  20211. * Calculate relative position change from the point of view of behind the front of the mesh.
  20212. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20213. * Supports definition of mesh facing forward or backward
  20214. * @param amountRight defines the distance on the right axis
  20215. * @param amountUp defines the distance on the up axis
  20216. * @param amountForward defines the distance on the forward axis
  20217. * @returns the new displacement vector
  20218. */
  20219. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20220. var rotMatrix = new BABYLON.Matrix();
  20221. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20222. rotQuaternion.toRotationMatrix(rotMatrix);
  20223. var translationDelta = BABYLON.Vector3.Zero();
  20224. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20225. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20226. return translationDelta;
  20227. };
  20228. // ================================== Point of View Rotation =================================
  20229. /**
  20230. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20231. * Supports definition of mesh facing forward or backward
  20232. * @param flipBack defines the flip
  20233. * @param twirlClockwise defines the twirl
  20234. * @param tiltRight defines the tilt
  20235. * @returns the current mesh
  20236. */
  20237. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20238. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20239. return this;
  20240. };
  20241. /**
  20242. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20243. * Supports definition of mesh facing forward or backward.
  20244. * @param flipBack defines the flip
  20245. * @param twirlClockwise defines the twirl
  20246. * @param tiltRight defines the tilt
  20247. * @returns the new rotation vector
  20248. */
  20249. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20250. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20251. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20252. };
  20253. /**
  20254. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20255. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20256. * @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
  20257. * @returns the new bounding vectors
  20258. */
  20259. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20260. if (includeDescendants === void 0) { includeDescendants = true; }
  20261. if (predicate === void 0) { predicate = null; }
  20262. // Ensures that all world matrix will be recomputed.
  20263. this.getScene().incrementRenderId();
  20264. this.computeWorldMatrix(true);
  20265. var min;
  20266. var max;
  20267. var boundingInfo = this.getBoundingInfo();
  20268. if (!this.subMeshes) {
  20269. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20270. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20271. }
  20272. else {
  20273. min = boundingInfo.boundingBox.minimumWorld;
  20274. max = boundingInfo.boundingBox.maximumWorld;
  20275. }
  20276. if (includeDescendants) {
  20277. var descendants = this.getDescendants(false);
  20278. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20279. var descendant = descendants_1[_i];
  20280. var childMesh = descendant;
  20281. childMesh.computeWorldMatrix(true);
  20282. // Filters meshes based on custom predicate function.
  20283. if (predicate && !predicate(childMesh)) {
  20284. continue;
  20285. }
  20286. //make sure we have the needed params to get mix and max
  20287. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20288. continue;
  20289. }
  20290. var childBoundingInfo = childMesh.getBoundingInfo();
  20291. var boundingBox = childBoundingInfo.boundingBox;
  20292. var minBox = boundingBox.minimumWorld;
  20293. var maxBox = boundingBox.maximumWorld;
  20294. BABYLON.Tools.CheckExtends(minBox, min, max);
  20295. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20296. }
  20297. }
  20298. return {
  20299. min: min,
  20300. max: max
  20301. };
  20302. };
  20303. /** @hidden */
  20304. AbstractMesh.prototype._updateBoundingInfo = function () {
  20305. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20306. this._boundingInfo.update(this.worldMatrixFromCache);
  20307. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20308. return this;
  20309. };
  20310. /** @hidden */
  20311. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20312. if (!this.subMeshes) {
  20313. return this;
  20314. }
  20315. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20316. var subMesh = this.subMeshes[subIndex];
  20317. if (!subMesh.IsGlobal) {
  20318. subMesh.updateBoundingInfo(matrix);
  20319. }
  20320. }
  20321. return this;
  20322. };
  20323. /** @hidden */
  20324. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20325. // Bounding info
  20326. this._updateBoundingInfo();
  20327. };
  20328. /**
  20329. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20330. * A mesh is in the frustum if its bounding box intersects the frustum
  20331. * @param frustumPlanes defines the frustum to test
  20332. * @returns true if the mesh is in the frustum planes
  20333. */
  20334. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20335. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20336. };
  20337. /**
  20338. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20339. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20340. * @param frustumPlanes defines the frustum to test
  20341. * @returns true if the mesh is completely in the frustum planes
  20342. */
  20343. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20344. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20345. };
  20346. /**
  20347. * True if the mesh intersects another mesh or a SolidParticle object
  20348. * @param mesh defines a target mesh or SolidParticle to test
  20349. * @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)
  20350. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20351. * @returns true if there is an intersection
  20352. */
  20353. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20354. if (precise === void 0) { precise = false; }
  20355. if (!this._boundingInfo || !mesh._boundingInfo) {
  20356. return false;
  20357. }
  20358. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20359. return true;
  20360. }
  20361. if (includeDescendants) {
  20362. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20363. var child = _a[_i];
  20364. if (child.intersectsMesh(mesh, precise, true)) {
  20365. return true;
  20366. }
  20367. }
  20368. }
  20369. return false;
  20370. };
  20371. /**
  20372. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20373. * @param point defines the point to test
  20374. * @returns true if there is an intersection
  20375. */
  20376. AbstractMesh.prototype.intersectsPoint = function (point) {
  20377. if (!this._boundingInfo) {
  20378. return false;
  20379. }
  20380. return this._boundingInfo.intersectsPoint(point);
  20381. };
  20382. /**
  20383. * Gets the current physics impostor
  20384. * @see http://doc.babylonjs.com/features/physics_engine
  20385. * @returns a physics impostor or null
  20386. */
  20387. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20388. return this.physicsImpostor;
  20389. };
  20390. /**
  20391. * Gets the position of the current mesh in camera space
  20392. * @param camera defines the camera to use
  20393. * @returns a position
  20394. */
  20395. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20396. if (camera === void 0) { camera = null; }
  20397. if (!camera) {
  20398. camera = this.getScene().activeCamera;
  20399. }
  20400. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20401. };
  20402. /**
  20403. * Returns the distance from the mesh to the active camera
  20404. * @param camera defines the camera to use
  20405. * @returns the distance
  20406. */
  20407. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20408. if (camera === void 0) { camera = null; }
  20409. if (!camera) {
  20410. camera = this.getScene().activeCamera;
  20411. }
  20412. return this.absolutePosition.subtract(camera.position).length();
  20413. };
  20414. /**
  20415. * Apply a physic impulse to the mesh
  20416. * @param force defines the force to apply
  20417. * @param contactPoint defines where to apply the force
  20418. * @returns the current mesh
  20419. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20420. */
  20421. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20422. if (!this.physicsImpostor) {
  20423. return this;
  20424. }
  20425. this.physicsImpostor.applyImpulse(force, contactPoint);
  20426. return this;
  20427. };
  20428. /**
  20429. * Creates a physic joint between two meshes
  20430. * @param otherMesh defines the other mesh to use
  20431. * @param pivot1 defines the pivot to use on this mesh
  20432. * @param pivot2 defines the pivot to use on the other mesh
  20433. * @param options defines additional options (can be plugin dependent)
  20434. * @returns the current mesh
  20435. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20436. */
  20437. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20438. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20439. return this;
  20440. }
  20441. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20442. mainPivot: pivot1,
  20443. connectedPivot: pivot2,
  20444. nativeParams: options
  20445. });
  20446. return this;
  20447. };
  20448. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20449. // Collisions
  20450. /**
  20451. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20452. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20453. */
  20454. get: function () {
  20455. return this._checkCollisions;
  20456. },
  20457. set: function (collisionEnabled) {
  20458. this._checkCollisions = collisionEnabled;
  20459. if (this.getScene().workerCollisions) {
  20460. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20461. }
  20462. },
  20463. enumerable: true,
  20464. configurable: true
  20465. });
  20466. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20467. /**
  20468. * Gets Collider object used to compute collisions (not physics)
  20469. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20470. */
  20471. get: function () {
  20472. return this._collider;
  20473. },
  20474. enumerable: true,
  20475. configurable: true
  20476. });
  20477. /**
  20478. * Move the mesh using collision engine
  20479. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20480. * @param displacement defines the requested displacement vector
  20481. * @returns the current mesh
  20482. */
  20483. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20484. var globalPosition = this.getAbsolutePosition();
  20485. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20486. if (!this._collider) {
  20487. this._collider = new BABYLON.Collider();
  20488. }
  20489. this._collider._radius = this.ellipsoid;
  20490. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20491. return this;
  20492. };
  20493. // Submeshes octree
  20494. /**
  20495. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20496. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20497. * @param maxCapacity defines the maximum size of each block (64 by default)
  20498. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20499. * @returns the new octree
  20500. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20501. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20502. */
  20503. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20504. if (maxCapacity === void 0) { maxCapacity = 64; }
  20505. if (maxDepth === void 0) { maxDepth = 2; }
  20506. if (!this._submeshesOctree) {
  20507. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20508. }
  20509. this.computeWorldMatrix(true);
  20510. var boundingInfo = this.getBoundingInfo();
  20511. // Update octree
  20512. var bbox = boundingInfo.boundingBox;
  20513. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20514. return this._submeshesOctree;
  20515. };
  20516. // Collisions
  20517. /** @hidden */
  20518. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20519. this._generatePointsArray();
  20520. if (!this._positions) {
  20521. return this;
  20522. }
  20523. // Transformation
  20524. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20525. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20526. subMesh._lastColliderWorldVertices = [];
  20527. subMesh._trianglePlanes = [];
  20528. var start = subMesh.verticesStart;
  20529. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20530. for (var i = start; i < end; i++) {
  20531. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20532. }
  20533. }
  20534. // Collide
  20535. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20536. if (collider.collisionFound) {
  20537. collider.collidedMesh = this;
  20538. }
  20539. return this;
  20540. };
  20541. /** @hidden */
  20542. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20543. var subMeshes;
  20544. var len;
  20545. // Octrees
  20546. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20547. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20548. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20549. len = intersections.length;
  20550. subMeshes = intersections.data;
  20551. }
  20552. else {
  20553. subMeshes = this.subMeshes;
  20554. len = subMeshes.length;
  20555. }
  20556. for (var index = 0; index < len; index++) {
  20557. var subMesh = subMeshes[index];
  20558. // Bounding test
  20559. if (len > 1 && !subMesh._checkCollision(collider))
  20560. continue;
  20561. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20562. }
  20563. return this;
  20564. };
  20565. /** @hidden */
  20566. AbstractMesh.prototype._checkCollision = function (collider) {
  20567. // Bounding box test
  20568. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20569. return this;
  20570. // Transformation matrix
  20571. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20572. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20573. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20574. return this;
  20575. };
  20576. // Picking
  20577. /** @hidden */
  20578. AbstractMesh.prototype._generatePointsArray = function () {
  20579. return false;
  20580. };
  20581. /**
  20582. * Checks if the passed Ray intersects with the mesh
  20583. * @param ray defines the ray to use
  20584. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20585. * @returns the picking info
  20586. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20587. */
  20588. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20589. var pickingInfo = new BABYLON.PickingInfo();
  20590. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20591. return pickingInfo;
  20592. }
  20593. if (!this._generatePointsArray()) {
  20594. return pickingInfo;
  20595. }
  20596. var intersectInfo = null;
  20597. // Octrees
  20598. var subMeshes;
  20599. var len;
  20600. if (this._submeshesOctree && this.useOctreeForPicking) {
  20601. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20602. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20603. len = intersections.length;
  20604. subMeshes = intersections.data;
  20605. }
  20606. else {
  20607. subMeshes = this.subMeshes;
  20608. len = subMeshes.length;
  20609. }
  20610. for (var index = 0; index < len; index++) {
  20611. var subMesh = subMeshes[index];
  20612. // Bounding test
  20613. if (len > 1 && !subMesh.canIntersects(ray))
  20614. continue;
  20615. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20616. if (currentIntersectInfo) {
  20617. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20618. intersectInfo = currentIntersectInfo;
  20619. intersectInfo.subMeshId = index;
  20620. if (fastCheck) {
  20621. break;
  20622. }
  20623. }
  20624. }
  20625. }
  20626. if (intersectInfo) {
  20627. // Get picked point
  20628. var world = this.getWorldMatrix();
  20629. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20630. var direction = ray.direction.clone();
  20631. direction = direction.scale(intersectInfo.distance);
  20632. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20633. var pickedPoint = worldOrigin.add(worldDirection);
  20634. // Return result
  20635. pickingInfo.hit = true;
  20636. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20637. pickingInfo.pickedPoint = pickedPoint;
  20638. pickingInfo.pickedMesh = this;
  20639. pickingInfo.bu = intersectInfo.bu || 0;
  20640. pickingInfo.bv = intersectInfo.bv || 0;
  20641. pickingInfo.faceId = intersectInfo.faceId;
  20642. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20643. return pickingInfo;
  20644. }
  20645. return pickingInfo;
  20646. };
  20647. /**
  20648. * Clones the current mesh
  20649. * @param name defines the mesh name
  20650. * @param newParent defines the new mesh parent
  20651. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20652. * @returns the new mesh
  20653. */
  20654. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20655. return null;
  20656. };
  20657. /**
  20658. * Disposes all the submeshes of the current meshnp
  20659. * @returns the current mesh
  20660. */
  20661. AbstractMesh.prototype.releaseSubMeshes = function () {
  20662. if (this.subMeshes) {
  20663. while (this.subMeshes.length) {
  20664. this.subMeshes[0].dispose();
  20665. }
  20666. }
  20667. else {
  20668. this.subMeshes = new Array();
  20669. }
  20670. return this;
  20671. };
  20672. /**
  20673. * Releases resources associated with this abstract mesh.
  20674. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20675. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20676. */
  20677. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20678. var _this = this;
  20679. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20680. var index;
  20681. // Smart Array Retainers.
  20682. this.getScene().freeActiveMeshes();
  20683. this.getScene().freeRenderingGroups();
  20684. // Action manager
  20685. if (this.actionManager !== undefined && this.actionManager !== null) {
  20686. this.actionManager.dispose();
  20687. this.actionManager = null;
  20688. }
  20689. // Skeleton
  20690. this._skeleton = null;
  20691. // Physics
  20692. if (this.physicsImpostor) {
  20693. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20694. }
  20695. // Intersections in progress
  20696. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20697. var other = this._intersectionsInProgress[index];
  20698. var pos = other._intersectionsInProgress.indexOf(this);
  20699. other._intersectionsInProgress.splice(pos, 1);
  20700. }
  20701. this._intersectionsInProgress = [];
  20702. // Lights
  20703. var lights = this.getScene().lights;
  20704. lights.forEach(function (light) {
  20705. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20706. if (meshIndex !== -1) {
  20707. light.includedOnlyMeshes.splice(meshIndex, 1);
  20708. }
  20709. meshIndex = light.excludedMeshes.indexOf(_this);
  20710. if (meshIndex !== -1) {
  20711. light.excludedMeshes.splice(meshIndex, 1);
  20712. }
  20713. // Shadow generators
  20714. var generator = light.getShadowGenerator();
  20715. if (generator) {
  20716. var shadowMap = generator.getShadowMap();
  20717. if (shadowMap && shadowMap.renderList) {
  20718. meshIndex = shadowMap.renderList.indexOf(_this);
  20719. if (meshIndex !== -1) {
  20720. shadowMap.renderList.splice(meshIndex, 1);
  20721. }
  20722. }
  20723. }
  20724. });
  20725. // Edges
  20726. if (this._edgesRenderer) {
  20727. this._edgesRenderer.dispose();
  20728. this._edgesRenderer = null;
  20729. }
  20730. // SubMeshes
  20731. if (this.getClassName() !== "InstancedMesh") {
  20732. this.releaseSubMeshes();
  20733. }
  20734. // Octree
  20735. var sceneOctree = this.getScene().selectionOctree;
  20736. if (sceneOctree !== undefined && sceneOctree !== null) {
  20737. var index = sceneOctree.dynamicContent.indexOf(this);
  20738. if (index !== -1) {
  20739. sceneOctree.dynamicContent.splice(index, 1);
  20740. }
  20741. }
  20742. // Query
  20743. var engine = this.getScene().getEngine();
  20744. if (this._occlusionQuery) {
  20745. this._isOcclusionQueryInProgress = false;
  20746. engine.deleteQuery(this._occlusionQuery);
  20747. this._occlusionQuery = null;
  20748. }
  20749. // Engine
  20750. engine.wipeCaches();
  20751. // Remove from scene
  20752. this.getScene().removeMesh(this);
  20753. if (disposeMaterialAndTextures) {
  20754. if (this.material) {
  20755. this.material.dispose(false, true);
  20756. }
  20757. }
  20758. if (!doNotRecurse) {
  20759. // Particles
  20760. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20761. if (this.getScene().particleSystems[index].emitter === this) {
  20762. this.getScene().particleSystems[index].dispose();
  20763. index--;
  20764. }
  20765. }
  20766. }
  20767. // facet data
  20768. if (this._facetDataEnabled) {
  20769. this.disableFacetData();
  20770. }
  20771. this.onAfterWorldMatrixUpdateObservable.clear();
  20772. this.onCollideObservable.clear();
  20773. this.onCollisionPositionChangeObservable.clear();
  20774. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20775. };
  20776. /**
  20777. * Adds the passed mesh as a child to the current mesh
  20778. * @param mesh defines the child mesh
  20779. * @returns the current mesh
  20780. */
  20781. AbstractMesh.prototype.addChild = function (mesh) {
  20782. mesh.setParent(this);
  20783. return this;
  20784. };
  20785. /**
  20786. * Removes the passed mesh from the current mesh children list
  20787. * @param mesh defines the child mesh
  20788. * @returns the current mesh
  20789. */
  20790. AbstractMesh.prototype.removeChild = function (mesh) {
  20791. mesh.setParent(null);
  20792. return this;
  20793. };
  20794. // Facet data
  20795. /** @hidden */
  20796. AbstractMesh.prototype._initFacetData = function () {
  20797. if (!this._facetNormals) {
  20798. this._facetNormals = new Array();
  20799. }
  20800. if (!this._facetPositions) {
  20801. this._facetPositions = new Array();
  20802. }
  20803. if (!this._facetPartitioning) {
  20804. this._facetPartitioning = new Array();
  20805. }
  20806. this._facetNb = (this.getIndices().length / 3) | 0;
  20807. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20808. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20809. for (var f = 0; f < this._facetNb; f++) {
  20810. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20811. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20812. }
  20813. this._facetDataEnabled = true;
  20814. return this;
  20815. };
  20816. /**
  20817. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20818. * This method can be called within the render loop.
  20819. * 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
  20820. * @returns the current mesh
  20821. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20822. */
  20823. AbstractMesh.prototype.updateFacetData = function () {
  20824. if (!this._facetDataEnabled) {
  20825. this._initFacetData();
  20826. }
  20827. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20828. var indices = this.getIndices();
  20829. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20830. var bInfo = this.getBoundingInfo();
  20831. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20832. // init arrays, matrix and sort function on first call
  20833. this._facetDepthSortEnabled = true;
  20834. if (indices instanceof Uint16Array) {
  20835. this._depthSortedIndices = new Uint16Array(indices);
  20836. }
  20837. else if (indices instanceof Uint32Array) {
  20838. this._depthSortedIndices = new Uint32Array(indices);
  20839. }
  20840. else {
  20841. var needs32bits = false;
  20842. for (var i = 0; i < indices.length; i++) {
  20843. if (indices[i] > 65535) {
  20844. needs32bits = true;
  20845. break;
  20846. }
  20847. }
  20848. if (needs32bits) {
  20849. this._depthSortedIndices = new Uint32Array(indices);
  20850. }
  20851. else {
  20852. this._depthSortedIndices = new Uint16Array(indices);
  20853. }
  20854. }
  20855. this._facetDepthSortFunction = function (f1, f2) {
  20856. return (f2.sqDistance - f1.sqDistance);
  20857. };
  20858. if (!this._facetDepthSortFrom) {
  20859. var camera = this.getScene().activeCamera;
  20860. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20861. }
  20862. this._depthSortedFacets = [];
  20863. for (var f = 0; f < this._facetNb; f++) {
  20864. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20865. this._depthSortedFacets.push(depthSortedFacet);
  20866. }
  20867. this._invertedMatrix = BABYLON.Matrix.Identity();
  20868. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20869. }
  20870. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20871. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20872. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20873. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20874. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20875. this._subDiv.max = this._partitioningSubdivisions;
  20876. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20877. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20878. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20879. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20880. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20881. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20882. // set the parameters for ComputeNormals()
  20883. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20884. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20885. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20886. this._facetParameters.bInfo = bInfo;
  20887. this._facetParameters.bbSize = this._bbSize;
  20888. this._facetParameters.subDiv = this._subDiv;
  20889. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20890. this._facetParameters.depthSort = this._facetDepthSort;
  20891. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20892. this.computeWorldMatrix(true);
  20893. this._worldMatrix.invertToRef(this._invertedMatrix);
  20894. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20895. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20896. }
  20897. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20898. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20899. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20900. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20901. var l = (this._depthSortedIndices.length / 3) | 0;
  20902. for (var f = 0; f < l; f++) {
  20903. var sind = this._depthSortedFacets[f].ind;
  20904. this._depthSortedIndices[f * 3] = indices[sind];
  20905. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20906. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20907. }
  20908. this.updateIndices(this._depthSortedIndices);
  20909. }
  20910. return this;
  20911. };
  20912. /**
  20913. * Returns the facetLocalNormals array.
  20914. * The normals are expressed in the mesh local spac
  20915. * @returns an array of Vector3
  20916. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20917. */
  20918. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20919. if (!this._facetNormals) {
  20920. this.updateFacetData();
  20921. }
  20922. return this._facetNormals;
  20923. };
  20924. /**
  20925. * Returns the facetLocalPositions array.
  20926. * The facet positions are expressed in the mesh local space
  20927. * @returns an array of Vector3
  20928. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20929. */
  20930. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20931. if (!this._facetPositions) {
  20932. this.updateFacetData();
  20933. }
  20934. return this._facetPositions;
  20935. };
  20936. /**
  20937. * Returns the facetLocalPartioning array
  20938. * @returns an array of array of numbers
  20939. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20940. */
  20941. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20942. if (!this._facetPartitioning) {
  20943. this.updateFacetData();
  20944. }
  20945. return this._facetPartitioning;
  20946. };
  20947. /**
  20948. * Returns the i-th facet position in the world system.
  20949. * This method allocates a new Vector3 per call
  20950. * @param i defines the facet index
  20951. * @returns a new Vector3
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20953. */
  20954. AbstractMesh.prototype.getFacetPosition = function (i) {
  20955. var pos = BABYLON.Vector3.Zero();
  20956. this.getFacetPositionToRef(i, pos);
  20957. return pos;
  20958. };
  20959. /**
  20960. * Sets the reference Vector3 with the i-th facet position in the world system
  20961. * @param i defines the facet index
  20962. * @param ref defines the target vector
  20963. * @returns the current mesh
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20965. */
  20966. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20967. var localPos = (this.getFacetLocalPositions())[i];
  20968. var world = this.getWorldMatrix();
  20969. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20970. return this;
  20971. };
  20972. /**
  20973. * Returns the i-th facet normal in the world system.
  20974. * This method allocates a new Vector3 per call
  20975. * @param i defines the facet index
  20976. * @returns a new Vector3
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetNormal = function (i) {
  20980. var norm = BABYLON.Vector3.Zero();
  20981. this.getFacetNormalToRef(i, norm);
  20982. return norm;
  20983. };
  20984. /**
  20985. * Sets the reference Vector3 with the i-th facet normal in the world system
  20986. * @param i defines the facet index
  20987. * @param ref defines the target vector
  20988. * @returns the current mesh
  20989. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20990. */
  20991. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20992. var localNorm = (this.getFacetLocalNormals())[i];
  20993. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20994. return this;
  20995. };
  20996. /**
  20997. * 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)
  20998. * @param x defines x coordinate
  20999. * @param y defines y coordinate
  21000. * @param z defines z coordinate
  21001. * @returns the array of facet indexes
  21002. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21003. */
  21004. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21005. var bInfo = this.getBoundingInfo();
  21006. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21007. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21008. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21009. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21010. return null;
  21011. }
  21012. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21013. };
  21014. /**
  21015. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21016. * @param projected sets as the (x,y,z) world projection on the facet
  21017. * @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
  21018. * @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
  21019. * @param x defines x coordinate
  21020. * @param y defines y coordinate
  21021. * @param z defines z coordinate
  21022. * @returns the face index if found (or null instead)
  21023. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21024. */
  21025. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21026. if (checkFace === void 0) { checkFace = false; }
  21027. if (facing === void 0) { facing = true; }
  21028. var world = this.getWorldMatrix();
  21029. var invMat = BABYLON.Tmp.Matrix[5];
  21030. world.invertToRef(invMat);
  21031. var invVect = BABYLON.Tmp.Vector3[8];
  21032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21033. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21034. if (projected) {
  21035. // tranform the local computed projected vector to world coordinates
  21036. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21037. }
  21038. return closest;
  21039. };
  21040. /**
  21041. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21042. * @param projected sets as the (x,y,z) local projection on the facet
  21043. * @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
  21044. * @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
  21045. * @param x defines x coordinate
  21046. * @param y defines y coordinate
  21047. * @param z defines z coordinate
  21048. * @returns the face index if found (or null instead)
  21049. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21050. */
  21051. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21052. if (checkFace === void 0) { checkFace = false; }
  21053. if (facing === void 0) { facing = true; }
  21054. var closest = null;
  21055. var tmpx = 0.0;
  21056. var tmpy = 0.0;
  21057. var tmpz = 0.0;
  21058. var d = 0.0; // tmp dot facet normal * facet position
  21059. var t0 = 0.0;
  21060. var projx = 0.0;
  21061. var projy = 0.0;
  21062. var projz = 0.0;
  21063. // Get all the facets in the same partitioning block than (x, y, z)
  21064. var facetPositions = this.getFacetLocalPositions();
  21065. var facetNormals = this.getFacetLocalNormals();
  21066. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21067. if (!facetsInBlock) {
  21068. return null;
  21069. }
  21070. // Get the closest facet to (x, y, z)
  21071. var shortest = Number.MAX_VALUE; // init distance vars
  21072. var tmpDistance = shortest;
  21073. var fib; // current facet in the block
  21074. var norm; // current facet normal
  21075. var p0; // current facet barycenter position
  21076. // loop on all the facets in the current partitioning block
  21077. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21078. fib = facetsInBlock[idx];
  21079. norm = facetNormals[fib];
  21080. p0 = facetPositions[fib];
  21081. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21082. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21083. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21084. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21085. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21086. projx = x + norm.x * t0;
  21087. projy = y + norm.y * t0;
  21088. projz = z + norm.z * t0;
  21089. tmpx = projx - x;
  21090. tmpy = projy - y;
  21091. tmpz = projz - z;
  21092. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21093. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21094. shortest = tmpDistance;
  21095. closest = fib;
  21096. if (projected) {
  21097. projected.x = projx;
  21098. projected.y = projy;
  21099. projected.z = projz;
  21100. }
  21101. }
  21102. }
  21103. }
  21104. return closest;
  21105. };
  21106. /**
  21107. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21108. * @returns the parameters
  21109. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21110. */
  21111. AbstractMesh.prototype.getFacetDataParameters = function () {
  21112. return this._facetParameters;
  21113. };
  21114. /**
  21115. * Disables the feature FacetData and frees the related memory
  21116. * @returns the current mesh
  21117. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21118. */
  21119. AbstractMesh.prototype.disableFacetData = function () {
  21120. if (this._facetDataEnabled) {
  21121. this._facetDataEnabled = false;
  21122. this._facetPositions = new Array();
  21123. this._facetNormals = new Array();
  21124. this._facetPartitioning = new Array();
  21125. this._facetParameters = null;
  21126. this._depthSortedIndices = new Uint32Array(0);
  21127. }
  21128. return this;
  21129. };
  21130. /**
  21131. * Updates the AbstractMesh indices array
  21132. * @param indices defines the data source
  21133. * @returns the current mesh
  21134. */
  21135. AbstractMesh.prototype.updateIndices = function (indices) {
  21136. return this;
  21137. };
  21138. /**
  21139. * Creates new normals data for the mesh
  21140. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21141. * @returns the current mesh
  21142. */
  21143. AbstractMesh.prototype.createNormals = function (updatable) {
  21144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21145. var indices = this.getIndices();
  21146. var normals;
  21147. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21148. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21149. }
  21150. else {
  21151. normals = [];
  21152. }
  21153. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21154. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21155. return this;
  21156. };
  21157. /**
  21158. * Align the mesh with a normal
  21159. * @param normal defines the normal to use
  21160. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21161. * @returns the current mesh
  21162. */
  21163. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21164. if (!upDirection) {
  21165. upDirection = BABYLON.Axis.Y;
  21166. }
  21167. var axisX = BABYLON.Tmp.Vector3[0];
  21168. var axisZ = BABYLON.Tmp.Vector3[1];
  21169. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21170. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21171. if (this.rotationQuaternion) {
  21172. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21173. }
  21174. else {
  21175. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21176. }
  21177. return this;
  21178. };
  21179. /** @hidden */
  21180. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21181. var engine = this.getEngine();
  21182. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21183. this._isOccluded = false;
  21184. return;
  21185. }
  21186. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21187. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21188. if (isOcclusionQueryAvailable) {
  21189. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21190. this._isOcclusionQueryInProgress = false;
  21191. this._occlusionInternalRetryCounter = 0;
  21192. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21193. }
  21194. else {
  21195. this._occlusionInternalRetryCounter++;
  21196. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21197. this._isOcclusionQueryInProgress = false;
  21198. this._occlusionInternalRetryCounter = 0;
  21199. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21200. // if strict continue the last state of the object.
  21201. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21202. }
  21203. else {
  21204. return;
  21205. }
  21206. }
  21207. }
  21208. // Todo. Move into an occlusion query component.
  21209. var scene = this.getScene();
  21210. if (scene.getBoundingBoxRenderer) {
  21211. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21212. if (!this._occlusionQuery) {
  21213. this._occlusionQuery = engine.createQuery();
  21214. }
  21215. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21216. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21217. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21218. this._isOcclusionQueryInProgress = true;
  21219. }
  21220. };
  21221. /** No occlusion */
  21222. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21223. /** Occlusion set to optimisitic */
  21224. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21225. /** Occlusion set to strict */
  21226. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21227. /** Use an accurante occlusion algorithm */
  21228. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21229. /** Use a conservative occlusion algorithm */
  21230. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21231. return AbstractMesh;
  21232. }(BABYLON.TransformNode));
  21233. BABYLON.AbstractMesh = AbstractMesh;
  21234. })(BABYLON || (BABYLON = {}));
  21235. //# sourceMappingURL=babylon.abstractMesh.js.map
  21236. var BABYLON;
  21237. (function (BABYLON) {
  21238. /**
  21239. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21240. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21241. * 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.
  21242. */
  21243. var Light = /** @class */ (function (_super) {
  21244. __extends(Light, _super);
  21245. /**
  21246. * Creates a Light object in the scene.
  21247. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21248. * @param name The firendly name of the light
  21249. * @param scene The scene the light belongs too
  21250. */
  21251. function Light(name, scene) {
  21252. var _this = _super.call(this, name, scene) || this;
  21253. /**
  21254. * Diffuse gives the basic color to an object.
  21255. */
  21256. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21257. /**
  21258. * Specular produces a highlight color on an object.
  21259. * Note: This is note affecting PBR materials.
  21260. */
  21261. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21262. /**
  21263. * Strength of the light.
  21264. * Note: By default it is define in the framework own unit.
  21265. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21266. */
  21267. _this.intensity = 1.0;
  21268. /**
  21269. * Defines how far from the source the light is impacting in scene units.
  21270. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21271. */
  21272. _this.range = Number.MAX_VALUE;
  21273. /**
  21274. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21275. * of light.
  21276. */
  21277. _this._photometricScale = 1.0;
  21278. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21279. _this._radius = 0.00001;
  21280. /**
  21281. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21282. * exceeding the number allowed of the materials.
  21283. */
  21284. _this.renderPriority = 0;
  21285. _this._shadowEnabled = true;
  21286. _this._excludeWithLayerMask = 0;
  21287. _this._includeOnlyWithLayerMask = 0;
  21288. _this._lightmapMode = 0;
  21289. /**
  21290. * @hidden Internal use only.
  21291. */
  21292. _this._excludedMeshesIds = new Array();
  21293. /**
  21294. * @hidden Internal use only.
  21295. */
  21296. _this._includedOnlyMeshesIds = new Array();
  21297. _this.getScene().addLight(_this);
  21298. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21299. _this._buildUniformLayout();
  21300. _this.includedOnlyMeshes = new Array();
  21301. _this.excludedMeshes = new Array();
  21302. _this._resyncMeshes();
  21303. return _this;
  21304. }
  21305. Object.defineProperty(Light.prototype, "intensityMode", {
  21306. /**
  21307. * Gets the photometric scale used to interpret the intensity.
  21308. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21309. */
  21310. get: function () {
  21311. return this._intensityMode;
  21312. },
  21313. /**
  21314. * Sets the photometric scale used to interpret the intensity.
  21315. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21316. */
  21317. set: function (value) {
  21318. this._intensityMode = value;
  21319. this._computePhotometricScale();
  21320. },
  21321. enumerable: true,
  21322. configurable: true
  21323. });
  21324. ;
  21325. ;
  21326. Object.defineProperty(Light.prototype, "radius", {
  21327. /**
  21328. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21329. */
  21330. get: function () {
  21331. return this._radius;
  21332. },
  21333. /**
  21334. * sets the light radius used by PBR Materials to simulate soft area lights.
  21335. */
  21336. set: function (value) {
  21337. this._radius = value;
  21338. this._computePhotometricScale();
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. ;
  21344. ;
  21345. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21346. /**
  21347. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21348. * the current shadow generator.
  21349. */
  21350. get: function () {
  21351. return this._shadowEnabled;
  21352. },
  21353. /**
  21354. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21355. * the current shadow generator.
  21356. */
  21357. set: function (value) {
  21358. if (this._shadowEnabled === value) {
  21359. return;
  21360. }
  21361. this._shadowEnabled = value;
  21362. this._markMeshesAsLightDirty();
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21368. /**
  21369. * Gets the only meshes impacted by this light.
  21370. */
  21371. get: function () {
  21372. return this._includedOnlyMeshes;
  21373. },
  21374. /**
  21375. * Sets the only meshes impacted by this light.
  21376. */
  21377. set: function (value) {
  21378. this._includedOnlyMeshes = value;
  21379. this._hookArrayForIncludedOnly(value);
  21380. },
  21381. enumerable: true,
  21382. configurable: true
  21383. });
  21384. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21385. /**
  21386. * Gets the meshes not impacted by this light.
  21387. */
  21388. get: function () {
  21389. return this._excludedMeshes;
  21390. },
  21391. /**
  21392. * Sets the meshes not impacted by this light.
  21393. */
  21394. set: function (value) {
  21395. this._excludedMeshes = value;
  21396. this._hookArrayForExcluded(value);
  21397. },
  21398. enumerable: true,
  21399. configurable: true
  21400. });
  21401. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21402. /**
  21403. * Gets the layer id use to find what meshes are not impacted by the light.
  21404. * Inactive if 0
  21405. */
  21406. get: function () {
  21407. return this._excludeWithLayerMask;
  21408. },
  21409. /**
  21410. * Sets the layer id use to find what meshes are not impacted by the light.
  21411. * Inactive if 0
  21412. */
  21413. set: function (value) {
  21414. this._excludeWithLayerMask = value;
  21415. this._resyncMeshes();
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21421. /**
  21422. * Gets the layer id use to find what meshes are impacted by the light.
  21423. * Inactive if 0
  21424. */
  21425. get: function () {
  21426. return this._includeOnlyWithLayerMask;
  21427. },
  21428. /**
  21429. * Sets the layer id use to find what meshes are impacted by the light.
  21430. * Inactive if 0
  21431. */
  21432. set: function (value) {
  21433. this._includeOnlyWithLayerMask = value;
  21434. this._resyncMeshes();
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(Light.prototype, "lightmapMode", {
  21440. /**
  21441. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21442. */
  21443. get: function () {
  21444. return this._lightmapMode;
  21445. },
  21446. /**
  21447. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21448. */
  21449. set: function (value) {
  21450. if (this._lightmapMode === value) {
  21451. return;
  21452. }
  21453. this._lightmapMode = value;
  21454. this._markMeshesAsLightDirty();
  21455. },
  21456. enumerable: true,
  21457. configurable: true
  21458. });
  21459. /**
  21460. * Returns the string "Light".
  21461. * @returns the class name
  21462. */
  21463. Light.prototype.getClassName = function () {
  21464. return "Light";
  21465. };
  21466. /**
  21467. * Converts the light information to a readable string for debug purpose.
  21468. * @param fullDetails Supports for multiple levels of logging within scene loading
  21469. * @returns the human readable light info
  21470. */
  21471. Light.prototype.toString = function (fullDetails) {
  21472. var ret = "Name: " + this.name;
  21473. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21474. if (this.animations) {
  21475. for (var i = 0; i < this.animations.length; i++) {
  21476. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21477. }
  21478. }
  21479. if (fullDetails) {
  21480. }
  21481. return ret;
  21482. };
  21483. /**
  21484. * Set the enabled state of this node.
  21485. * @param value - the new enabled state
  21486. */
  21487. Light.prototype.setEnabled = function (value) {
  21488. _super.prototype.setEnabled.call(this, value);
  21489. this._resyncMeshes();
  21490. };
  21491. /**
  21492. * Returns the Light associated shadow generator if any.
  21493. * @return the associated shadow generator.
  21494. */
  21495. Light.prototype.getShadowGenerator = function () {
  21496. return this._shadowGenerator;
  21497. };
  21498. /**
  21499. * Returns a Vector3, the absolute light position in the World.
  21500. * @returns the world space position of the light
  21501. */
  21502. Light.prototype.getAbsolutePosition = function () {
  21503. return BABYLON.Vector3.Zero();
  21504. };
  21505. /**
  21506. * Specifies if the light will affect the passed mesh.
  21507. * @param mesh The mesh to test against the light
  21508. * @return true the mesh is affected otherwise, false.
  21509. */
  21510. Light.prototype.canAffectMesh = function (mesh) {
  21511. if (!mesh) {
  21512. return true;
  21513. }
  21514. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21515. return false;
  21516. }
  21517. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21518. return false;
  21519. }
  21520. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21521. return false;
  21522. }
  21523. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21524. return false;
  21525. }
  21526. return true;
  21527. };
  21528. /**
  21529. * Computes and Returns the light World matrix.
  21530. * @returns the world matrix
  21531. */
  21532. Light.prototype.getWorldMatrix = function () {
  21533. this._currentRenderId = this.getScene().getRenderId();
  21534. this._childRenderId = this._currentRenderId;
  21535. var worldMatrix = this._getWorldMatrix();
  21536. if (this.parent && this.parent.getWorldMatrix) {
  21537. if (!this._parentedWorldMatrix) {
  21538. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21539. }
  21540. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21541. this._markSyncedWithParent();
  21542. return this._parentedWorldMatrix;
  21543. }
  21544. return worldMatrix;
  21545. };
  21546. /**
  21547. * Sort function to order lights for rendering.
  21548. * @param a First Light object to compare to second.
  21549. * @param b Second Light object to compare first.
  21550. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21551. */
  21552. Light.CompareLightsPriority = function (a, b) {
  21553. //shadow-casting lights have priority over non-shadow-casting lights
  21554. //the renderPrioirty is a secondary sort criterion
  21555. if (a.shadowEnabled !== b.shadowEnabled) {
  21556. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21557. }
  21558. return b.renderPriority - a.renderPriority;
  21559. };
  21560. /**
  21561. * Releases resources associated with this node.
  21562. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21563. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21564. */
  21565. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21566. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21567. if (this._shadowGenerator) {
  21568. this._shadowGenerator.dispose();
  21569. this._shadowGenerator = null;
  21570. }
  21571. // Animations
  21572. this.getScene().stopAnimation(this);
  21573. // Remove from meshes
  21574. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21575. var mesh = _a[_i];
  21576. mesh._removeLightSource(this);
  21577. }
  21578. this._uniformBuffer.dispose();
  21579. // Remove from scene
  21580. this.getScene().removeLight(this);
  21581. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21582. };
  21583. /**
  21584. * Returns the light type ID (integer).
  21585. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21586. */
  21587. Light.prototype.getTypeID = function () {
  21588. return 0;
  21589. };
  21590. /**
  21591. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21592. * @returns the scaled intensity in intensity mode unit
  21593. */
  21594. Light.prototype.getScaledIntensity = function () {
  21595. return this._photometricScale * this.intensity;
  21596. };
  21597. /**
  21598. * Returns a new Light object, named "name", from the current one.
  21599. * @param name The name of the cloned light
  21600. * @returns the new created light
  21601. */
  21602. Light.prototype.clone = function (name) {
  21603. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21604. if (!constructor) {
  21605. return null;
  21606. }
  21607. return BABYLON.SerializationHelper.Clone(constructor, this);
  21608. };
  21609. /**
  21610. * Serializes the current light into a Serialization object.
  21611. * @returns the serialized object.
  21612. */
  21613. Light.prototype.serialize = function () {
  21614. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21615. // Type
  21616. serializationObject.type = this.getTypeID();
  21617. // Parent
  21618. if (this.parent) {
  21619. serializationObject.parentId = this.parent.id;
  21620. }
  21621. // Inclusion / exclusions
  21622. if (this.excludedMeshes.length > 0) {
  21623. serializationObject.excludedMeshesIds = [];
  21624. this.excludedMeshes.forEach(function (mesh) {
  21625. serializationObject.excludedMeshesIds.push(mesh.id);
  21626. });
  21627. }
  21628. if (this.includedOnlyMeshes.length > 0) {
  21629. serializationObject.includedOnlyMeshesIds = [];
  21630. this.includedOnlyMeshes.forEach(function (mesh) {
  21631. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21632. });
  21633. }
  21634. // Animations
  21635. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21636. serializationObject.ranges = this.serializeAnimationRanges();
  21637. return serializationObject;
  21638. };
  21639. /**
  21640. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21641. * This new light is named "name" and added to the passed scene.
  21642. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21643. * @param name The friendly name of the light
  21644. * @param scene The scene the new light will belong to
  21645. * @returns the constructor function
  21646. */
  21647. Light.GetConstructorFromName = function (type, name, scene) {
  21648. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21649. if (constructorFunc) {
  21650. return constructorFunc;
  21651. }
  21652. // Default to no light for none present once.
  21653. return null;
  21654. };
  21655. /**
  21656. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21657. * @param parsedLight The JSON representation of the light
  21658. * @param scene The scene to create the parsed light in
  21659. * @returns the created light after parsing
  21660. */
  21661. Light.Parse = function (parsedLight, scene) {
  21662. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21663. if (!constructor) {
  21664. return null;
  21665. }
  21666. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21667. // Inclusion / exclusions
  21668. if (parsedLight.excludedMeshesIds) {
  21669. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21670. }
  21671. if (parsedLight.includedOnlyMeshesIds) {
  21672. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21673. }
  21674. // Parent
  21675. if (parsedLight.parentId) {
  21676. light._waitingParentId = parsedLight.parentId;
  21677. }
  21678. // Animations
  21679. if (parsedLight.animations) {
  21680. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21681. var parsedAnimation = parsedLight.animations[animationIndex];
  21682. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21683. }
  21684. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21685. }
  21686. if (parsedLight.autoAnimate) {
  21687. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21688. }
  21689. return light;
  21690. };
  21691. Light.prototype._hookArrayForExcluded = function (array) {
  21692. var _this = this;
  21693. var oldPush = array.push;
  21694. array.push = function () {
  21695. var items = [];
  21696. for (var _i = 0; _i < arguments.length; _i++) {
  21697. items[_i] = arguments[_i];
  21698. }
  21699. var result = oldPush.apply(array, items);
  21700. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21701. var item = items_1[_a];
  21702. item._resyncLighSource(_this);
  21703. }
  21704. return result;
  21705. };
  21706. var oldSplice = array.splice;
  21707. array.splice = function (index, deleteCount) {
  21708. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21709. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21710. var item = deleted_1[_i];
  21711. item._resyncLighSource(_this);
  21712. }
  21713. return deleted;
  21714. };
  21715. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21716. var item = array_1[_i];
  21717. item._resyncLighSource(this);
  21718. }
  21719. };
  21720. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21721. var _this = this;
  21722. var oldPush = array.push;
  21723. array.push = function () {
  21724. var items = [];
  21725. for (var _i = 0; _i < arguments.length; _i++) {
  21726. items[_i] = arguments[_i];
  21727. }
  21728. var result = oldPush.apply(array, items);
  21729. _this._resyncMeshes();
  21730. return result;
  21731. };
  21732. var oldSplice = array.splice;
  21733. array.splice = function (index, deleteCount) {
  21734. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21735. _this._resyncMeshes();
  21736. return deleted;
  21737. };
  21738. this._resyncMeshes();
  21739. };
  21740. Light.prototype._resyncMeshes = function () {
  21741. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21742. var mesh = _a[_i];
  21743. mesh._resyncLighSource(this);
  21744. }
  21745. };
  21746. /**
  21747. * Forces the meshes to update their light related information in their rendering used effects
  21748. * @hidden Internal Use Only
  21749. */
  21750. Light.prototype._markMeshesAsLightDirty = function () {
  21751. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21752. var mesh = _a[_i];
  21753. if (mesh._lightSources.indexOf(this) !== -1) {
  21754. mesh._markSubMeshesAsLightDirty();
  21755. }
  21756. }
  21757. };
  21758. /**
  21759. * Recomputes the cached photometric scale if needed.
  21760. */
  21761. Light.prototype._computePhotometricScale = function () {
  21762. this._photometricScale = this._getPhotometricScale();
  21763. this.getScene().resetCachedMaterial();
  21764. };
  21765. /**
  21766. * Returns the Photometric Scale according to the light type and intensity mode.
  21767. */
  21768. Light.prototype._getPhotometricScale = function () {
  21769. var photometricScale = 0.0;
  21770. var lightTypeID = this.getTypeID();
  21771. //get photometric mode
  21772. var photometricMode = this.intensityMode;
  21773. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21774. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21775. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21776. }
  21777. else {
  21778. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21779. }
  21780. }
  21781. //compute photometric scale
  21782. switch (lightTypeID) {
  21783. case Light.LIGHTTYPEID_POINTLIGHT:
  21784. case Light.LIGHTTYPEID_SPOTLIGHT:
  21785. switch (photometricMode) {
  21786. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21787. photometricScale = 1.0 / (4.0 * Math.PI);
  21788. break;
  21789. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21790. photometricScale = 1.0;
  21791. break;
  21792. case Light.INTENSITYMODE_LUMINANCE:
  21793. photometricScale = this.radius * this.radius;
  21794. break;
  21795. }
  21796. break;
  21797. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21798. switch (photometricMode) {
  21799. case Light.INTENSITYMODE_ILLUMINANCE:
  21800. photometricScale = 1.0;
  21801. break;
  21802. case Light.INTENSITYMODE_LUMINANCE:
  21803. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21804. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21805. var apexAngleRadians = this.radius;
  21806. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21807. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21808. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21809. photometricScale = solidAngle;
  21810. break;
  21811. }
  21812. break;
  21813. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21814. // No fall off in hemisperic light.
  21815. photometricScale = 1.0;
  21816. break;
  21817. }
  21818. return photometricScale;
  21819. };
  21820. /**
  21821. * Reorder the light in the scene according to their defined priority.
  21822. * @hidden Internal Use Only
  21823. */
  21824. Light.prototype._reorderLightsInScene = function () {
  21825. var scene = this.getScene();
  21826. if (this._renderPriority != 0) {
  21827. scene.requireLightSorting = true;
  21828. }
  21829. this.getScene().sortLightsByPriority();
  21830. };
  21831. //lightmapMode Consts
  21832. /**
  21833. * If every light affecting the material is in this lightmapMode,
  21834. * material.lightmapTexture adds or multiplies
  21835. * (depends on material.useLightmapAsShadowmap)
  21836. * after every other light calculations.
  21837. */
  21838. Light.LIGHTMAP_DEFAULT = 0;
  21839. /**
  21840. * material.lightmapTexture as only diffuse lighting from this light
  21841. * adds only specular lighting from this light
  21842. * adds dynamic shadows
  21843. */
  21844. Light.LIGHTMAP_SPECULAR = 1;
  21845. /**
  21846. * material.lightmapTexture as only lighting
  21847. * no light calculation from this light
  21848. * only adds dynamic shadows from this light
  21849. */
  21850. Light.LIGHTMAP_SHADOWSONLY = 2;
  21851. // Intensity Mode Consts
  21852. /**
  21853. * Each light type uses the default quantity according to its type:
  21854. * point/spot lights use luminous intensity
  21855. * directional lights use illuminance
  21856. */
  21857. Light.INTENSITYMODE_AUTOMATIC = 0;
  21858. /**
  21859. * lumen (lm)
  21860. */
  21861. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21862. /**
  21863. * candela (lm/sr)
  21864. */
  21865. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21866. /**
  21867. * lux (lm/m^2)
  21868. */
  21869. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21870. /**
  21871. * nit (cd/m^2)
  21872. */
  21873. Light.INTENSITYMODE_LUMINANCE = 4;
  21874. // Light types ids const.
  21875. /**
  21876. * Light type const id of the point light.
  21877. */
  21878. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21879. /**
  21880. * Light type const id of the directional light.
  21881. */
  21882. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21883. /**
  21884. * Light type const id of the spot light.
  21885. */
  21886. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21887. /**
  21888. * Light type const id of the hemispheric light.
  21889. */
  21890. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21891. __decorate([
  21892. BABYLON.serializeAsColor3()
  21893. ], Light.prototype, "diffuse", void 0);
  21894. __decorate([
  21895. BABYLON.serializeAsColor3()
  21896. ], Light.prototype, "specular", void 0);
  21897. __decorate([
  21898. BABYLON.serialize()
  21899. ], Light.prototype, "intensity", void 0);
  21900. __decorate([
  21901. BABYLON.serialize()
  21902. ], Light.prototype, "range", void 0);
  21903. __decorate([
  21904. BABYLON.serialize()
  21905. ], Light.prototype, "intensityMode", null);
  21906. __decorate([
  21907. BABYLON.serialize()
  21908. ], Light.prototype, "radius", null);
  21909. __decorate([
  21910. BABYLON.serialize()
  21911. ], Light.prototype, "_renderPriority", void 0);
  21912. __decorate([
  21913. BABYLON.expandToProperty("_reorderLightsInScene")
  21914. ], Light.prototype, "renderPriority", void 0);
  21915. __decorate([
  21916. BABYLON.serialize("shadowEnabled")
  21917. ], Light.prototype, "_shadowEnabled", void 0);
  21918. __decorate([
  21919. BABYLON.serialize("excludeWithLayerMask")
  21920. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21921. __decorate([
  21922. BABYLON.serialize("includeOnlyWithLayerMask")
  21923. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21924. __decorate([
  21925. BABYLON.serialize("lightmapMode")
  21926. ], Light.prototype, "_lightmapMode", void 0);
  21927. return Light;
  21928. }(BABYLON.Node));
  21929. BABYLON.Light = Light;
  21930. })(BABYLON || (BABYLON = {}));
  21931. //# sourceMappingURL=babylon.light.js.map
  21932. var BABYLON;
  21933. (function (BABYLON) {
  21934. var Camera = /** @class */ (function (_super) {
  21935. __extends(Camera, _super);
  21936. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21937. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21938. var _this = _super.call(this, name, scene) || this;
  21939. /**
  21940. * The vector the camera should consider as up.
  21941. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21942. */
  21943. _this.upVector = BABYLON.Vector3.Up();
  21944. _this.orthoLeft = null;
  21945. _this.orthoRight = null;
  21946. _this.orthoBottom = null;
  21947. _this.orthoTop = null;
  21948. /**
  21949. * FOV is set in Radians. (default is 0.8)
  21950. */
  21951. _this.fov = 0.8;
  21952. _this.minZ = 1;
  21953. _this.maxZ = 10000.0;
  21954. _this.inertia = 0.9;
  21955. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21956. _this.isIntermediate = false;
  21957. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21958. /**
  21959. * Restricts the camera to viewing objects with the same layerMask.
  21960. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21961. */
  21962. _this.layerMask = 0x0FFFFFFF;
  21963. /**
  21964. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21965. */
  21966. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21967. // Camera rig members
  21968. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21969. _this._rigCameras = new Array();
  21970. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21971. _this._skipRendering = false;
  21972. _this.customRenderTargets = new Array();
  21973. // Observables
  21974. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21975. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21976. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21977. _this.onRestoreStateObservable = new BABYLON.Observable();
  21978. // Cache
  21979. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21980. _this._projectionMatrix = new BABYLON.Matrix();
  21981. _this._doNotComputeProjectionMatrix = false;
  21982. _this._worldMatrix = BABYLON.Matrix.Identity();
  21983. _this._postProcesses = new Array();
  21984. _this._transformMatrix = BABYLON.Matrix.Zero();
  21985. _this._activeMeshes = new BABYLON.SmartArray(256);
  21986. _this._globalPosition = BABYLON.Vector3.Zero();
  21987. _this._refreshFrustumPlanes = true;
  21988. _this.getScene().addCamera(_this);
  21989. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21990. _this.getScene().activeCamera = _this;
  21991. }
  21992. _this.position = position;
  21993. return _this;
  21994. }
  21995. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21996. get: function () {
  21997. return Camera._PERSPECTIVE_CAMERA;
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22003. get: function () {
  22004. return Camera._ORTHOGRAPHIC_CAMERA;
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22010. /**
  22011. * This is the default FOV mode for perspective cameras.
  22012. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22013. *
  22014. */
  22015. get: function () {
  22016. return Camera._FOVMODE_VERTICAL_FIXED;
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22022. /**
  22023. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22024. *
  22025. */
  22026. get: function () {
  22027. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22028. },
  22029. enumerable: true,
  22030. configurable: true
  22031. });
  22032. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22033. get: function () {
  22034. return Camera._RIG_MODE_NONE;
  22035. },
  22036. enumerable: true,
  22037. configurable: true
  22038. });
  22039. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22040. get: function () {
  22041. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22047. get: function () {
  22048. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22054. get: function () {
  22055. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22056. },
  22057. enumerable: true,
  22058. configurable: true
  22059. });
  22060. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22061. get: function () {
  22062. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22068. get: function () {
  22069. return Camera._RIG_MODE_VR;
  22070. },
  22071. enumerable: true,
  22072. configurable: true
  22073. });
  22074. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22075. get: function () {
  22076. return Camera._RIG_MODE_WEBVR;
  22077. },
  22078. enumerable: true,
  22079. configurable: true
  22080. });
  22081. /**
  22082. * Store current camera state (fov, position, etc..)
  22083. */
  22084. Camera.prototype.storeState = function () {
  22085. this._stateStored = true;
  22086. this._storedFov = this.fov;
  22087. return this;
  22088. };
  22089. /**
  22090. * Restores the camera state values if it has been stored. You must call storeState() first
  22091. */
  22092. Camera.prototype._restoreStateValues = function () {
  22093. if (!this._stateStored) {
  22094. return false;
  22095. }
  22096. this.fov = this._storedFov;
  22097. return true;
  22098. };
  22099. /**
  22100. * Restored camera state. You must call storeState() first
  22101. */
  22102. Camera.prototype.restoreState = function () {
  22103. if (this._restoreStateValues()) {
  22104. this.onRestoreStateObservable.notifyObservers(this);
  22105. return true;
  22106. }
  22107. return false;
  22108. };
  22109. Camera.prototype.getClassName = function () {
  22110. return "Camera";
  22111. };
  22112. /**
  22113. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22114. */
  22115. Camera.prototype.toString = function (fullDetails) {
  22116. var ret = "Name: " + this.name;
  22117. ret += ", type: " + this.getClassName();
  22118. if (this.animations) {
  22119. for (var i = 0; i < this.animations.length; i++) {
  22120. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22121. }
  22122. }
  22123. if (fullDetails) {
  22124. }
  22125. return ret;
  22126. };
  22127. Object.defineProperty(Camera.prototype, "globalPosition", {
  22128. get: function () {
  22129. return this._globalPosition;
  22130. },
  22131. enumerable: true,
  22132. configurable: true
  22133. });
  22134. Camera.prototype.getActiveMeshes = function () {
  22135. return this._activeMeshes;
  22136. };
  22137. Camera.prototype.isActiveMesh = function (mesh) {
  22138. return (this._activeMeshes.indexOf(mesh) !== -1);
  22139. };
  22140. /**
  22141. * Is this camera ready to be used/rendered
  22142. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22143. * @return true if the camera is ready
  22144. */
  22145. Camera.prototype.isReady = function (completeCheck) {
  22146. if (completeCheck === void 0) { completeCheck = false; }
  22147. if (completeCheck) {
  22148. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22149. var pp = _a[_i];
  22150. if (pp && !pp.isReady()) {
  22151. return false;
  22152. }
  22153. }
  22154. }
  22155. return _super.prototype.isReady.call(this, completeCheck);
  22156. };
  22157. //Cache
  22158. Camera.prototype._initCache = function () {
  22159. _super.prototype._initCache.call(this);
  22160. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22161. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22162. this._cache.mode = undefined;
  22163. this._cache.minZ = undefined;
  22164. this._cache.maxZ = undefined;
  22165. this._cache.fov = undefined;
  22166. this._cache.fovMode = undefined;
  22167. this._cache.aspectRatio = undefined;
  22168. this._cache.orthoLeft = undefined;
  22169. this._cache.orthoRight = undefined;
  22170. this._cache.orthoBottom = undefined;
  22171. this._cache.orthoTop = undefined;
  22172. this._cache.renderWidth = undefined;
  22173. this._cache.renderHeight = undefined;
  22174. };
  22175. Camera.prototype._updateCache = function (ignoreParentClass) {
  22176. if (!ignoreParentClass) {
  22177. _super.prototype._updateCache.call(this);
  22178. }
  22179. this._cache.position.copyFrom(this.position);
  22180. this._cache.upVector.copyFrom(this.upVector);
  22181. };
  22182. // Synchronized
  22183. Camera.prototype._isSynchronized = function () {
  22184. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22185. };
  22186. Camera.prototype._isSynchronizedViewMatrix = function () {
  22187. if (!_super.prototype._isSynchronized.call(this))
  22188. return false;
  22189. return this._cache.position.equals(this.position)
  22190. && this._cache.upVector.equals(this.upVector)
  22191. && this.isSynchronizedWithParent();
  22192. };
  22193. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22194. var check = this._cache.mode === this.mode
  22195. && this._cache.minZ === this.minZ
  22196. && this._cache.maxZ === this.maxZ;
  22197. if (!check) {
  22198. return false;
  22199. }
  22200. var engine = this.getEngine();
  22201. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22202. check = this._cache.fov === this.fov
  22203. && this._cache.fovMode === this.fovMode
  22204. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22205. }
  22206. else {
  22207. check = this._cache.orthoLeft === this.orthoLeft
  22208. && this._cache.orthoRight === this.orthoRight
  22209. && this._cache.orthoBottom === this.orthoBottom
  22210. && this._cache.orthoTop === this.orthoTop
  22211. && this._cache.renderWidth === engine.getRenderWidth()
  22212. && this._cache.renderHeight === engine.getRenderHeight();
  22213. }
  22214. return check;
  22215. };
  22216. // Controls
  22217. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22218. };
  22219. Camera.prototype.detachControl = function (element) {
  22220. };
  22221. Camera.prototype.update = function () {
  22222. this._checkInputs();
  22223. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22224. this._updateRigCameras();
  22225. }
  22226. };
  22227. Camera.prototype._checkInputs = function () {
  22228. this.onAfterCheckInputsObservable.notifyObservers(this);
  22229. };
  22230. Object.defineProperty(Camera.prototype, "rigCameras", {
  22231. get: function () {
  22232. return this._rigCameras;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22238. get: function () {
  22239. return this._rigPostProcess;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. /**
  22245. * Internal, gets the first post proces.
  22246. * @returns the first post process to be run on this camera.
  22247. */
  22248. Camera.prototype._getFirstPostProcess = function () {
  22249. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22250. if (this._postProcesses[ppIndex] !== null) {
  22251. return this._postProcesses[ppIndex];
  22252. }
  22253. }
  22254. return null;
  22255. };
  22256. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22257. // invalidate framebuffer
  22258. var firstPostProcess = this._getFirstPostProcess();
  22259. if (firstPostProcess) {
  22260. firstPostProcess.markTextureDirty();
  22261. }
  22262. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22263. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22264. var cam = this._rigCameras[i];
  22265. var rigPostProcess = cam._rigPostProcess;
  22266. // for VR rig, there does not have to be a post process
  22267. if (rigPostProcess) {
  22268. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22269. if (isPass) {
  22270. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22271. cam.isIntermediate = this._postProcesses.length === 0;
  22272. }
  22273. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22274. rigPostProcess.markTextureDirty();
  22275. }
  22276. else {
  22277. cam._postProcesses = this._postProcesses.slice(0);
  22278. }
  22279. }
  22280. };
  22281. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22282. if (insertAt === void 0) { insertAt = null; }
  22283. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22284. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22285. return 0;
  22286. }
  22287. if (insertAt == null || insertAt < 0) {
  22288. this._postProcesses.push(postProcess);
  22289. }
  22290. else if (this._postProcesses[insertAt] === null) {
  22291. this._postProcesses[insertAt] = postProcess;
  22292. }
  22293. else {
  22294. this._postProcesses.splice(insertAt, 0, postProcess);
  22295. }
  22296. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22297. return this._postProcesses.indexOf(postProcess);
  22298. };
  22299. Camera.prototype.detachPostProcess = function (postProcess) {
  22300. var idx = this._postProcesses.indexOf(postProcess);
  22301. if (idx !== -1) {
  22302. this._postProcesses[idx] = null;
  22303. }
  22304. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22305. };
  22306. Camera.prototype.getWorldMatrix = function () {
  22307. if (this._isSynchronizedViewMatrix()) {
  22308. return this._worldMatrix;
  22309. }
  22310. // Getting the the view matrix will also compute the world matrix.
  22311. this.getViewMatrix();
  22312. return this._worldMatrix;
  22313. };
  22314. Camera.prototype._getViewMatrix = function () {
  22315. return BABYLON.Matrix.Identity();
  22316. };
  22317. Camera.prototype.getViewMatrix = function (force) {
  22318. if (!force && this._isSynchronizedViewMatrix()) {
  22319. return this._computedViewMatrix;
  22320. }
  22321. this.updateCache();
  22322. this._computedViewMatrix = this._getViewMatrix();
  22323. this._currentRenderId = this.getScene().getRenderId();
  22324. this._childRenderId = this._currentRenderId;
  22325. this._refreshFrustumPlanes = true;
  22326. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22327. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22328. }
  22329. this.onViewMatrixChangedObservable.notifyObservers(this);
  22330. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22331. return this._computedViewMatrix;
  22332. };
  22333. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22334. this._doNotComputeProjectionMatrix = true;
  22335. if (projection !== undefined) {
  22336. this._projectionMatrix = projection;
  22337. }
  22338. };
  22339. ;
  22340. Camera.prototype.unfreezeProjectionMatrix = function () {
  22341. this._doNotComputeProjectionMatrix = false;
  22342. };
  22343. ;
  22344. Camera.prototype.getProjectionMatrix = function (force) {
  22345. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22346. return this._projectionMatrix;
  22347. }
  22348. // Cache
  22349. this._cache.mode = this.mode;
  22350. this._cache.minZ = this.minZ;
  22351. this._cache.maxZ = this.maxZ;
  22352. // Matrix
  22353. this._refreshFrustumPlanes = true;
  22354. var engine = this.getEngine();
  22355. var scene = this.getScene();
  22356. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22357. this._cache.fov = this.fov;
  22358. this._cache.fovMode = this.fovMode;
  22359. this._cache.aspectRatio = engine.getAspectRatio(this);
  22360. if (this.minZ <= 0) {
  22361. this.minZ = 0.1;
  22362. }
  22363. if (scene.useRightHandedSystem) {
  22364. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22365. }
  22366. else {
  22367. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22368. }
  22369. }
  22370. else {
  22371. var halfWidth = engine.getRenderWidth() / 2.0;
  22372. var halfHeight = engine.getRenderHeight() / 2.0;
  22373. if (scene.useRightHandedSystem) {
  22374. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22375. }
  22376. else {
  22377. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22378. }
  22379. this._cache.orthoLeft = this.orthoLeft;
  22380. this._cache.orthoRight = this.orthoRight;
  22381. this._cache.orthoBottom = this.orthoBottom;
  22382. this._cache.orthoTop = this.orthoTop;
  22383. this._cache.renderWidth = engine.getRenderWidth();
  22384. this._cache.renderHeight = engine.getRenderHeight();
  22385. }
  22386. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22387. return this._projectionMatrix;
  22388. };
  22389. Camera.prototype.getTranformationMatrix = function () {
  22390. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22391. return this._transformMatrix;
  22392. };
  22393. Camera.prototype.updateFrustumPlanes = function () {
  22394. if (!this._refreshFrustumPlanes) {
  22395. return;
  22396. }
  22397. this.getTranformationMatrix();
  22398. if (!this._frustumPlanes) {
  22399. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22400. }
  22401. else {
  22402. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22403. }
  22404. this._refreshFrustumPlanes = false;
  22405. };
  22406. Camera.prototype.isInFrustum = function (target) {
  22407. this.updateFrustumPlanes();
  22408. return target.isInFrustum(this._frustumPlanes);
  22409. };
  22410. Camera.prototype.isCompletelyInFrustum = function (target) {
  22411. this.updateFrustumPlanes();
  22412. return target.isCompletelyInFrustum(this._frustumPlanes);
  22413. };
  22414. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22415. if (length === void 0) { length = 100; }
  22416. if (!transform) {
  22417. transform = this.getWorldMatrix();
  22418. }
  22419. if (!origin) {
  22420. origin = this.position;
  22421. }
  22422. var forward = new BABYLON.Vector3(0, 0, 1);
  22423. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22424. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22425. return new BABYLON.Ray(origin, direction, length);
  22426. };
  22427. /**
  22428. * Releases resources associated with this node.
  22429. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22430. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22431. */
  22432. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22433. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22434. // Observables
  22435. this.onViewMatrixChangedObservable.clear();
  22436. this.onProjectionMatrixChangedObservable.clear();
  22437. this.onAfterCheckInputsObservable.clear();
  22438. this.onRestoreStateObservable.clear();
  22439. // Inputs
  22440. if (this.inputs) {
  22441. this.inputs.clear();
  22442. }
  22443. // Animations
  22444. this.getScene().stopAnimation(this);
  22445. // Remove from scene
  22446. this.getScene().removeCamera(this);
  22447. while (this._rigCameras.length > 0) {
  22448. var camera = this._rigCameras.pop();
  22449. if (camera) {
  22450. camera.dispose();
  22451. }
  22452. }
  22453. // Postprocesses
  22454. if (this._rigPostProcess) {
  22455. this._rigPostProcess.dispose(this);
  22456. this._rigPostProcess = null;
  22457. this._postProcesses = [];
  22458. }
  22459. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22460. this._rigPostProcess = null;
  22461. this._postProcesses = [];
  22462. }
  22463. else {
  22464. var i = this._postProcesses.length;
  22465. while (--i >= 0) {
  22466. var postProcess = this._postProcesses[i];
  22467. if (postProcess) {
  22468. postProcess.dispose(this);
  22469. }
  22470. }
  22471. }
  22472. // Render targets
  22473. var i = this.customRenderTargets.length;
  22474. while (--i >= 0) {
  22475. this.customRenderTargets[i].dispose();
  22476. }
  22477. this.customRenderTargets = [];
  22478. // Active Meshes
  22479. this._activeMeshes.dispose();
  22480. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22481. };
  22482. Object.defineProperty(Camera.prototype, "leftCamera", {
  22483. // ---- Camera rigs section ----
  22484. get: function () {
  22485. if (this._rigCameras.length < 1) {
  22486. return null;
  22487. }
  22488. return this._rigCameras[0];
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Camera.prototype, "rightCamera", {
  22494. get: function () {
  22495. if (this._rigCameras.length < 2) {
  22496. return null;
  22497. }
  22498. return this._rigCameras[1];
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Camera.prototype.getLeftTarget = function () {
  22504. if (this._rigCameras.length < 1) {
  22505. return null;
  22506. }
  22507. return this._rigCameras[0].getTarget();
  22508. };
  22509. Camera.prototype.getRightTarget = function () {
  22510. if (this._rigCameras.length < 2) {
  22511. return null;
  22512. }
  22513. return this._rigCameras[1].getTarget();
  22514. };
  22515. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22516. if (this.cameraRigMode === mode) {
  22517. return;
  22518. }
  22519. while (this._rigCameras.length > 0) {
  22520. var camera = this._rigCameras.pop();
  22521. if (camera) {
  22522. camera.dispose();
  22523. }
  22524. }
  22525. this.cameraRigMode = mode;
  22526. this._cameraRigParams = {};
  22527. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22528. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22529. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22530. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22531. // create the rig cameras, unless none
  22532. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22533. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22534. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22535. if (leftCamera && rightCamera) {
  22536. this._rigCameras.push(leftCamera);
  22537. this._rigCameras.push(rightCamera);
  22538. }
  22539. }
  22540. switch (this.cameraRigMode) {
  22541. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22542. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22543. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22544. break;
  22545. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22546. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22547. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22548. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22549. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22550. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22551. break;
  22552. case Camera.RIG_MODE_VR:
  22553. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22554. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22555. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22556. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22557. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22558. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22559. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22560. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22561. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22562. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22563. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22564. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22565. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22566. if (metrics.compensateDistortion) {
  22567. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22568. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22569. }
  22570. break;
  22571. case Camera.RIG_MODE_WEBVR:
  22572. if (rigParams.vrDisplay) {
  22573. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22574. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22575. //Left eye
  22576. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22577. this._rigCameras[0].setCameraRigParameter("left", true);
  22578. //leaving this for future reference
  22579. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22580. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22581. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22582. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22583. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22584. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22585. this._rigCameras[0].parent = this;
  22586. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22587. //Right eye
  22588. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22589. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22590. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22591. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22592. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22593. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22594. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22595. this._rigCameras[1].parent = this;
  22596. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22597. if (Camera.UseAlternateWebVRRendering) {
  22598. this._rigCameras[1]._skipRendering = true;
  22599. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22600. }
  22601. }
  22602. break;
  22603. }
  22604. this._cascadePostProcessesToRigCams();
  22605. this.update();
  22606. };
  22607. Camera.prototype._getVRProjectionMatrix = function () {
  22608. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22609. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22610. return this._projectionMatrix;
  22611. };
  22612. Camera.prototype._updateCameraRotationMatrix = function () {
  22613. //Here for WebVR
  22614. };
  22615. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22616. //Here for WebVR
  22617. };
  22618. /**
  22619. * This function MUST be overwritten by the different WebVR cameras available.
  22620. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22621. */
  22622. Camera.prototype._getWebVRProjectionMatrix = function () {
  22623. return BABYLON.Matrix.Identity();
  22624. };
  22625. /**
  22626. * This function MUST be overwritten by the different WebVR cameras available.
  22627. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22628. */
  22629. Camera.prototype._getWebVRViewMatrix = function () {
  22630. return BABYLON.Matrix.Identity();
  22631. };
  22632. Camera.prototype.setCameraRigParameter = function (name, value) {
  22633. if (!this._cameraRigParams) {
  22634. this._cameraRigParams = {};
  22635. }
  22636. this._cameraRigParams[name] = value;
  22637. //provisionnally:
  22638. if (name === "interaxialDistance") {
  22639. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22640. }
  22641. };
  22642. /**
  22643. * needs to be overridden by children so sub has required properties to be copied
  22644. */
  22645. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22646. return null;
  22647. };
  22648. /**
  22649. * May need to be overridden by children
  22650. */
  22651. Camera.prototype._updateRigCameras = function () {
  22652. for (var i = 0; i < this._rigCameras.length; i++) {
  22653. this._rigCameras[i].minZ = this.minZ;
  22654. this._rigCameras[i].maxZ = this.maxZ;
  22655. this._rigCameras[i].fov = this.fov;
  22656. }
  22657. // only update viewport when ANAGLYPH
  22658. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22659. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22660. }
  22661. };
  22662. Camera.prototype._setupInputs = function () {
  22663. };
  22664. Camera.prototype.serialize = function () {
  22665. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22666. // Type
  22667. serializationObject.type = this.getClassName();
  22668. // Parent
  22669. if (this.parent) {
  22670. serializationObject.parentId = this.parent.id;
  22671. }
  22672. if (this.inputs) {
  22673. this.inputs.serialize(serializationObject);
  22674. }
  22675. // Animations
  22676. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22677. serializationObject.ranges = this.serializeAnimationRanges();
  22678. return serializationObject;
  22679. };
  22680. Camera.prototype.clone = function (name) {
  22681. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22682. };
  22683. Camera.prototype.getDirection = function (localAxis) {
  22684. var result = BABYLON.Vector3.Zero();
  22685. this.getDirectionToRef(localAxis, result);
  22686. return result;
  22687. };
  22688. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22689. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22690. };
  22691. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22692. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22693. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22694. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22695. interaxial_distance: interaxial_distance,
  22696. isStereoscopicSideBySide: isStereoscopicSideBySide
  22697. });
  22698. if (constructorFunc) {
  22699. return constructorFunc;
  22700. }
  22701. // Default to universal camera
  22702. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22703. };
  22704. Camera.prototype.computeWorldMatrix = function () {
  22705. return this.getWorldMatrix();
  22706. };
  22707. Camera.Parse = function (parsedCamera, scene) {
  22708. var type = parsedCamera.type;
  22709. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22710. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22711. // Parent
  22712. if (parsedCamera.parentId) {
  22713. camera._waitingParentId = parsedCamera.parentId;
  22714. }
  22715. //If camera has an input manager, let it parse inputs settings
  22716. if (camera.inputs) {
  22717. camera.inputs.parse(parsedCamera);
  22718. camera._setupInputs();
  22719. }
  22720. if (camera.setPosition) { // need to force position
  22721. camera.position.copyFromFloats(0, 0, 0);
  22722. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22723. }
  22724. // Target
  22725. if (parsedCamera.target) {
  22726. if (camera.setTarget) {
  22727. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22728. }
  22729. }
  22730. // Apply 3d rig, when found
  22731. if (parsedCamera.cameraRigMode) {
  22732. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22733. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22734. }
  22735. // Animations
  22736. if (parsedCamera.animations) {
  22737. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22738. var parsedAnimation = parsedCamera.animations[animationIndex];
  22739. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22740. }
  22741. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22742. }
  22743. if (parsedCamera.autoAnimate) {
  22744. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22745. }
  22746. return camera;
  22747. };
  22748. // Statics
  22749. Camera._PERSPECTIVE_CAMERA = 0;
  22750. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22751. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22752. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22753. Camera._RIG_MODE_NONE = 0;
  22754. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22755. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22756. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22757. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22758. Camera._RIG_MODE_VR = 20;
  22759. Camera._RIG_MODE_WEBVR = 21;
  22760. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22761. Camera.UseAlternateWebVRRendering = false;
  22762. __decorate([
  22763. BABYLON.serializeAsVector3()
  22764. ], Camera.prototype, "position", void 0);
  22765. __decorate([
  22766. BABYLON.serializeAsVector3()
  22767. ], Camera.prototype, "upVector", void 0);
  22768. __decorate([
  22769. BABYLON.serialize()
  22770. ], Camera.prototype, "orthoLeft", void 0);
  22771. __decorate([
  22772. BABYLON.serialize()
  22773. ], Camera.prototype, "orthoRight", void 0);
  22774. __decorate([
  22775. BABYLON.serialize()
  22776. ], Camera.prototype, "orthoBottom", void 0);
  22777. __decorate([
  22778. BABYLON.serialize()
  22779. ], Camera.prototype, "orthoTop", void 0);
  22780. __decorate([
  22781. BABYLON.serialize()
  22782. ], Camera.prototype, "fov", void 0);
  22783. __decorate([
  22784. BABYLON.serialize()
  22785. ], Camera.prototype, "minZ", void 0);
  22786. __decorate([
  22787. BABYLON.serialize()
  22788. ], Camera.prototype, "maxZ", void 0);
  22789. __decorate([
  22790. BABYLON.serialize()
  22791. ], Camera.prototype, "inertia", void 0);
  22792. __decorate([
  22793. BABYLON.serialize()
  22794. ], Camera.prototype, "mode", void 0);
  22795. __decorate([
  22796. BABYLON.serialize()
  22797. ], Camera.prototype, "layerMask", void 0);
  22798. __decorate([
  22799. BABYLON.serialize()
  22800. ], Camera.prototype, "fovMode", void 0);
  22801. __decorate([
  22802. BABYLON.serialize()
  22803. ], Camera.prototype, "cameraRigMode", void 0);
  22804. __decorate([
  22805. BABYLON.serialize()
  22806. ], Camera.prototype, "interaxialDistance", void 0);
  22807. __decorate([
  22808. BABYLON.serialize()
  22809. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22810. return Camera;
  22811. }(BABYLON.Node));
  22812. BABYLON.Camera = Camera;
  22813. })(BABYLON || (BABYLON = {}));
  22814. //# sourceMappingURL=babylon.camera.js.map
  22815. var BABYLON;
  22816. (function (BABYLON) {
  22817. var RenderingManager = /** @class */ (function () {
  22818. function RenderingManager(scene) {
  22819. this._renderingGroups = new Array();
  22820. this._autoClearDepthStencil = {};
  22821. this._customOpaqueSortCompareFn = {};
  22822. this._customAlphaTestSortCompareFn = {};
  22823. this._customTransparentSortCompareFn = {};
  22824. this._renderinGroupInfo = null;
  22825. this._scene = scene;
  22826. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22827. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22828. }
  22829. }
  22830. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22831. if (depth === void 0) { depth = true; }
  22832. if (stencil === void 0) { stencil = true; }
  22833. if (this._depthStencilBufferAlreadyCleaned) {
  22834. return;
  22835. }
  22836. this._scene.getEngine().clear(null, false, depth, stencil);
  22837. this._depthStencilBufferAlreadyCleaned = true;
  22838. };
  22839. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22840. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22841. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22842. var info = null;
  22843. if (observable) {
  22844. if (!this._renderinGroupInfo) {
  22845. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22846. }
  22847. info = this._renderinGroupInfo;
  22848. info.scene = this._scene;
  22849. info.camera = this._scene.activeCamera;
  22850. }
  22851. // Dispatch sprites
  22852. if (renderSprites) {
  22853. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22854. var manager = this._scene.spriteManagers[index];
  22855. this.dispatchSprites(manager);
  22856. }
  22857. }
  22858. // Render
  22859. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22860. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22861. var renderingGroup = this._renderingGroups[index];
  22862. if (!renderingGroup && !observable)
  22863. continue;
  22864. var renderingGroupMask = 0;
  22865. // Fire PRECLEAR stage
  22866. if (observable && info) {
  22867. renderingGroupMask = Math.pow(2, index);
  22868. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22869. info.renderingGroupId = index;
  22870. observable.notifyObservers(info, renderingGroupMask);
  22871. }
  22872. // Clear depth/stencil if needed
  22873. if (RenderingManager.AUTOCLEAR) {
  22874. var autoClear = this._autoClearDepthStencil[index];
  22875. if (autoClear && autoClear.autoClear) {
  22876. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22877. }
  22878. }
  22879. if (observable && info) {
  22880. // Fire PREOPAQUE stage
  22881. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22882. observable.notifyObservers(info, renderingGroupMask);
  22883. // Fire PRETRANSPARENT stage
  22884. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22885. observable.notifyObservers(info, renderingGroupMask);
  22886. }
  22887. if (renderingGroup) {
  22888. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22889. var step = _a[_i];
  22890. step.action(index);
  22891. }
  22892. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22893. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22894. var step = _c[_b];
  22895. step.action(index);
  22896. }
  22897. }
  22898. // Fire POSTTRANSPARENT stage
  22899. if (observable && info) {
  22900. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22901. observable.notifyObservers(info, renderingGroupMask);
  22902. }
  22903. }
  22904. };
  22905. RenderingManager.prototype.reset = function () {
  22906. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22907. var renderingGroup = this._renderingGroups[index];
  22908. if (renderingGroup) {
  22909. renderingGroup.prepare();
  22910. }
  22911. }
  22912. };
  22913. RenderingManager.prototype.dispose = function () {
  22914. this.freeRenderingGroups();
  22915. this._renderingGroups.length = 0;
  22916. };
  22917. /**
  22918. * Clear the info related to rendering groups preventing retention points during dispose.
  22919. */
  22920. RenderingManager.prototype.freeRenderingGroups = function () {
  22921. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22922. var renderingGroup = this._renderingGroups[index];
  22923. if (renderingGroup) {
  22924. renderingGroup.dispose();
  22925. }
  22926. }
  22927. };
  22928. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22929. if (this._renderingGroups[renderingGroupId] === undefined) {
  22930. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22931. }
  22932. };
  22933. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22934. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22935. this._prepareRenderingGroup(renderingGroupId);
  22936. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22937. };
  22938. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22939. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22940. this._prepareRenderingGroup(renderingGroupId);
  22941. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22942. };
  22943. /**
  22944. * @param subMesh The submesh to dispatch
  22945. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22946. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22947. */
  22948. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22949. if (mesh === undefined) {
  22950. mesh = subMesh.getMesh();
  22951. }
  22952. var renderingGroupId = mesh.renderingGroupId || 0;
  22953. this._prepareRenderingGroup(renderingGroupId);
  22954. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22955. };
  22956. /**
  22957. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22958. * This allowed control for front to back rendering or reversly depending of the special needs.
  22959. *
  22960. * @param renderingGroupId The rendering group id corresponding to its index
  22961. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22962. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22963. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22964. */
  22965. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22966. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22967. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22968. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22969. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22970. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22971. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22972. if (this._renderingGroups[renderingGroupId]) {
  22973. var group = this._renderingGroups[renderingGroupId];
  22974. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22975. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22976. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22977. }
  22978. };
  22979. /**
  22980. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22981. *
  22982. * @param renderingGroupId The rendering group id corresponding to its index
  22983. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22984. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22985. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22986. */
  22987. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22988. if (depth === void 0) { depth = true; }
  22989. if (stencil === void 0) { stencil = true; }
  22990. this._autoClearDepthStencil[renderingGroupId] = {
  22991. autoClear: autoClearDepthStencil,
  22992. depth: depth,
  22993. stencil: stencil
  22994. };
  22995. };
  22996. /**
  22997. * The max id used for rendering groups (not included)
  22998. */
  22999. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23000. /**
  23001. * The min id used for rendering groups (included)
  23002. */
  23003. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23004. /**
  23005. * Used to globally prevent autoclearing scenes.
  23006. */
  23007. RenderingManager.AUTOCLEAR = true;
  23008. return RenderingManager;
  23009. }());
  23010. BABYLON.RenderingManager = RenderingManager;
  23011. })(BABYLON || (BABYLON = {}));
  23012. //# sourceMappingURL=babylon.renderingManager.js.map
  23013. var BABYLON;
  23014. (function (BABYLON) {
  23015. var RenderingGroup = /** @class */ (function () {
  23016. /**
  23017. * Creates a new rendering group.
  23018. * @param index The rendering group index
  23019. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23020. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23021. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23022. */
  23023. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23024. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23025. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23026. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23027. this.index = index;
  23028. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23029. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23030. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23031. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23032. this._particleSystems = new BABYLON.SmartArray(256);
  23033. this._spriteManagers = new BABYLON.SmartArray(256);
  23034. this._edgesRenderers = new BABYLON.SmartArray(16);
  23035. this._scene = scene;
  23036. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23037. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23038. this.transparentSortCompareFn = transparentSortCompareFn;
  23039. }
  23040. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23041. /**
  23042. * Set the opaque sort comparison function.
  23043. * If null the sub meshes will be render in the order they were created
  23044. */
  23045. set: function (value) {
  23046. this._opaqueSortCompareFn = value;
  23047. if (value) {
  23048. this._renderOpaque = this.renderOpaqueSorted;
  23049. }
  23050. else {
  23051. this._renderOpaque = RenderingGroup.renderUnsorted;
  23052. }
  23053. },
  23054. enumerable: true,
  23055. configurable: true
  23056. });
  23057. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23058. /**
  23059. * Set the alpha test sort comparison function.
  23060. * If null the sub meshes will be render in the order they were created
  23061. */
  23062. set: function (value) {
  23063. this._alphaTestSortCompareFn = value;
  23064. if (value) {
  23065. this._renderAlphaTest = this.renderAlphaTestSorted;
  23066. }
  23067. else {
  23068. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23069. }
  23070. },
  23071. enumerable: true,
  23072. configurable: true
  23073. });
  23074. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23075. /**
  23076. * Set the transparent sort comparison function.
  23077. * If null the sub meshes will be render in the order they were created
  23078. */
  23079. set: function (value) {
  23080. if (value) {
  23081. this._transparentSortCompareFn = value;
  23082. }
  23083. else {
  23084. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23085. }
  23086. this._renderTransparent = this.renderTransparentSorted;
  23087. },
  23088. enumerable: true,
  23089. configurable: true
  23090. });
  23091. /**
  23092. * Render all the sub meshes contained in the group.
  23093. * @param customRenderFunction Used to override the default render behaviour of the group.
  23094. * @returns true if rendered some submeshes.
  23095. */
  23096. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23097. if (customRenderFunction) {
  23098. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23099. return;
  23100. }
  23101. var engine = this._scene.getEngine();
  23102. // Depth only
  23103. if (this._depthOnlySubMeshes.length !== 0) {
  23104. engine.setColorWrite(false);
  23105. this._renderAlphaTest(this._depthOnlySubMeshes);
  23106. engine.setColorWrite(true);
  23107. }
  23108. // Opaque
  23109. if (this._opaqueSubMeshes.length !== 0) {
  23110. this._renderOpaque(this._opaqueSubMeshes);
  23111. }
  23112. // Alpha test
  23113. if (this._alphaTestSubMeshes.length !== 0) {
  23114. this._renderAlphaTest(this._alphaTestSubMeshes);
  23115. }
  23116. var stencilState = engine.getStencilBuffer();
  23117. engine.setStencilBuffer(false);
  23118. // Sprites
  23119. if (renderSprites) {
  23120. this._renderSprites();
  23121. }
  23122. // Particles
  23123. if (renderParticles) {
  23124. this._renderParticles(activeMeshes);
  23125. }
  23126. if (this.onBeforeTransparentRendering) {
  23127. this.onBeforeTransparentRendering();
  23128. }
  23129. // Transparent
  23130. if (this._transparentSubMeshes.length !== 0) {
  23131. this._renderTransparent(this._transparentSubMeshes);
  23132. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23133. }
  23134. // Set back stencil to false in case it changes before the edge renderer.
  23135. engine.setStencilBuffer(false);
  23136. // Edges
  23137. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23138. this._edgesRenderers.data[edgesRendererIndex].render();
  23139. }
  23140. // Restore Stencil state.
  23141. engine.setStencilBuffer(stencilState);
  23142. };
  23143. /**
  23144. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23145. * @param subMeshes The submeshes to render
  23146. */
  23147. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23148. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23149. };
  23150. /**
  23151. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23152. * @param subMeshes The submeshes to render
  23153. */
  23154. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23155. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23156. };
  23157. /**
  23158. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23159. * @param subMeshes The submeshes to render
  23160. */
  23161. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23162. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23163. };
  23164. /**
  23165. * Renders the submeshes in a specified order.
  23166. * @param subMeshes The submeshes to sort before render
  23167. * @param sortCompareFn The comparison function use to sort
  23168. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23169. * @param transparent Specifies to activate blending if true
  23170. */
  23171. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23172. var subIndex = 0;
  23173. var subMesh;
  23174. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23175. for (; subIndex < subMeshes.length; subIndex++) {
  23176. subMesh = subMeshes.data[subIndex];
  23177. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23178. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23179. }
  23180. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23181. if (sortCompareFn) {
  23182. sortedArray.sort(sortCompareFn);
  23183. }
  23184. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23185. subMesh = sortedArray[subIndex];
  23186. if (transparent) {
  23187. var material = subMesh.getMaterial();
  23188. if (material && material.needDepthPrePass) {
  23189. var engine = material.getScene().getEngine();
  23190. engine.setColorWrite(false);
  23191. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23192. subMesh.render(false);
  23193. engine.setColorWrite(true);
  23194. }
  23195. }
  23196. subMesh.render(transparent);
  23197. }
  23198. };
  23199. /**
  23200. * Renders the submeshes in the order they were dispatched (no sort applied).
  23201. * @param subMeshes The submeshes to render
  23202. */
  23203. RenderingGroup.renderUnsorted = function (subMeshes) {
  23204. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23205. var submesh = subMeshes.data[subIndex];
  23206. submesh.render(false);
  23207. }
  23208. };
  23209. /**
  23210. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23211. * are rendered back to front if in the same alpha index.
  23212. *
  23213. * @param a The first submesh
  23214. * @param b The second submesh
  23215. * @returns The result of the comparison
  23216. */
  23217. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23218. // Alpha index first
  23219. if (a._alphaIndex > b._alphaIndex) {
  23220. return 1;
  23221. }
  23222. if (a._alphaIndex < b._alphaIndex) {
  23223. return -1;
  23224. }
  23225. // Then distance to camera
  23226. return RenderingGroup.backToFrontSortCompare(a, b);
  23227. };
  23228. /**
  23229. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23230. * are rendered back to front.
  23231. *
  23232. * @param a The first submesh
  23233. * @param b The second submesh
  23234. * @returns The result of the comparison
  23235. */
  23236. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23237. // Then distance to camera
  23238. if (a._distanceToCamera < b._distanceToCamera) {
  23239. return 1;
  23240. }
  23241. if (a._distanceToCamera > b._distanceToCamera) {
  23242. return -1;
  23243. }
  23244. return 0;
  23245. };
  23246. /**
  23247. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23248. * are rendered front to back (prevent overdraw).
  23249. *
  23250. * @param a The first submesh
  23251. * @param b The second submesh
  23252. * @returns The result of the comparison
  23253. */
  23254. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23255. // Then distance to camera
  23256. if (a._distanceToCamera < b._distanceToCamera) {
  23257. return -1;
  23258. }
  23259. if (a._distanceToCamera > b._distanceToCamera) {
  23260. return 1;
  23261. }
  23262. return 0;
  23263. };
  23264. /**
  23265. * Resets the different lists of submeshes to prepare a new frame.
  23266. */
  23267. RenderingGroup.prototype.prepare = function () {
  23268. this._opaqueSubMeshes.reset();
  23269. this._transparentSubMeshes.reset();
  23270. this._alphaTestSubMeshes.reset();
  23271. this._depthOnlySubMeshes.reset();
  23272. this._particleSystems.reset();
  23273. this._spriteManagers.reset();
  23274. this._edgesRenderers.reset();
  23275. };
  23276. RenderingGroup.prototype.dispose = function () {
  23277. this._opaqueSubMeshes.dispose();
  23278. this._transparentSubMeshes.dispose();
  23279. this._alphaTestSubMeshes.dispose();
  23280. this._depthOnlySubMeshes.dispose();
  23281. this._particleSystems.dispose();
  23282. this._spriteManagers.dispose();
  23283. this._edgesRenderers.dispose();
  23284. };
  23285. /**
  23286. * Inserts the submesh in its correct queue depending on its material.
  23287. * @param subMesh The submesh to dispatch
  23288. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23289. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23290. */
  23291. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23292. // Get mesh and materials if not provided
  23293. if (mesh === undefined) {
  23294. mesh = subMesh.getMesh();
  23295. }
  23296. if (material === undefined) {
  23297. material = subMesh.getMaterial();
  23298. }
  23299. if (material === null || material === undefined) {
  23300. return;
  23301. }
  23302. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23303. this._transparentSubMeshes.push(subMesh);
  23304. }
  23305. else if (material.needAlphaTesting()) { // Alpha test
  23306. if (material.needDepthPrePass) {
  23307. this._depthOnlySubMeshes.push(subMesh);
  23308. }
  23309. this._alphaTestSubMeshes.push(subMesh);
  23310. }
  23311. else {
  23312. if (material.needDepthPrePass) {
  23313. this._depthOnlySubMeshes.push(subMesh);
  23314. }
  23315. this._opaqueSubMeshes.push(subMesh); // Opaque
  23316. }
  23317. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23318. this._edgesRenderers.push(mesh._edgesRenderer);
  23319. }
  23320. };
  23321. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23322. this._spriteManagers.push(spriteManager);
  23323. };
  23324. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23325. this._particleSystems.push(particleSystem);
  23326. };
  23327. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23328. if (this._particleSystems.length === 0) {
  23329. return;
  23330. }
  23331. // Particles
  23332. var activeCamera = this._scene.activeCamera;
  23333. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23334. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23335. var particleSystem = this._particleSystems.data[particleIndex];
  23336. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23337. continue;
  23338. }
  23339. var emitter = particleSystem.emitter;
  23340. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23341. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23342. }
  23343. }
  23344. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23345. };
  23346. RenderingGroup.prototype._renderSprites = function () {
  23347. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23348. return;
  23349. }
  23350. // Sprites
  23351. var activeCamera = this._scene.activeCamera;
  23352. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23353. for (var id = 0; id < this._spriteManagers.length; id++) {
  23354. var spriteManager = this._spriteManagers.data[id];
  23355. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23356. spriteManager.render();
  23357. }
  23358. }
  23359. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23360. };
  23361. return RenderingGroup;
  23362. }());
  23363. BABYLON.RenderingGroup = RenderingGroup;
  23364. })(BABYLON || (BABYLON = {}));
  23365. //# sourceMappingURL=babylon.renderingGroup.js.map
  23366. var BABYLON;
  23367. (function (BABYLON) {
  23368. /**
  23369. * Groups all the scene component constants in one place to ease maintenance.
  23370. * @hidden
  23371. */
  23372. var SceneComponentConstants = /** @class */ (function () {
  23373. function SceneComponentConstants() {
  23374. }
  23375. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23376. SceneComponentConstants.NAME_LAYER = "Layer";
  23377. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23378. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23379. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23380. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23381. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23382. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23383. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23384. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23385. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23386. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23387. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23388. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23389. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23390. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23391. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23392. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23393. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23394. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23395. return SceneComponentConstants;
  23396. }());
  23397. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23398. /**
  23399. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23400. * @hidden
  23401. */
  23402. var Stage = /** @class */ (function (_super) {
  23403. __extends(Stage, _super);
  23404. /**
  23405. * Hide ctor from the rest of the world.
  23406. * @param items The items to add.
  23407. */
  23408. function Stage(items) {
  23409. return _super.apply(this, items) || this;
  23410. }
  23411. /**
  23412. * Creates a new Stage.
  23413. * @returns A new instance of a Stage
  23414. */
  23415. Stage.Create = function () {
  23416. return Object.create(Stage.prototype);
  23417. };
  23418. /**
  23419. * Registers a step in an ordered way in the targeted stage.
  23420. * @param index Defines the position to register the step in
  23421. * @param component Defines the component attached to the step
  23422. * @param action Defines the action to launch during the step
  23423. */
  23424. Stage.prototype.registerStep = function (index, component, action) {
  23425. var i = 0;
  23426. var maxIndex = Number.MAX_VALUE;
  23427. for (; i < this.length && i < maxIndex; i++) {
  23428. var step = this[i];
  23429. maxIndex = step.index;
  23430. }
  23431. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23432. };
  23433. /**
  23434. * Clears all the steps from the stage.
  23435. */
  23436. Stage.prototype.clear = function () {
  23437. this.length = 0;
  23438. };
  23439. return Stage;
  23440. }(Array));
  23441. BABYLON.Stage = Stage;
  23442. })(BABYLON || (BABYLON = {}));
  23443. //# sourceMappingURL=babylon.sceneComponent.js.map
  23444. var BABYLON;
  23445. (function (BABYLON) {
  23446. /**
  23447. * Base class of the scene acting as a container for the different elements composing a scene.
  23448. * This class is dynamically extended by the different components of the scene increasing
  23449. * flexibility and reducing coupling
  23450. */
  23451. var AbstractScene = /** @class */ (function () {
  23452. function AbstractScene() {
  23453. /** All of the cameras added to this scene
  23454. * @see http://doc.babylonjs.com/babylon101/cameras
  23455. */
  23456. this.cameras = new Array();
  23457. /**
  23458. * All of the lights added to this scene
  23459. * @see http://doc.babylonjs.com/babylon101/lights
  23460. */
  23461. this.lights = new Array();
  23462. /**
  23463. * All of the (abstract) meshes added to this scene
  23464. */
  23465. this.meshes = new Array();
  23466. /**
  23467. * The list of skeletons added to the scene
  23468. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23469. */
  23470. this.skeletons = new Array();
  23471. /**
  23472. * All of the particle systems added to this scene
  23473. * @see http://doc.babylonjs.com/babylon101/particles
  23474. */
  23475. this.particleSystems = new Array();
  23476. /**
  23477. * Gets a list of Animations associated with the scene
  23478. */
  23479. this.animations = [];
  23480. /**
  23481. * All of the animation groups added to this scene
  23482. * @see http://doc.babylonjs.com/how_to/group
  23483. */
  23484. this.animationGroups = new Array();
  23485. /**
  23486. * All of the multi-materials added to this scene
  23487. * @see http://doc.babylonjs.com/how_to/multi_materials
  23488. */
  23489. this.multiMaterials = new Array();
  23490. /**
  23491. * All of the materials added to this scene
  23492. * @see http://doc.babylonjs.com/babylon101/materials
  23493. */
  23494. this.materials = new Array();
  23495. /**
  23496. * The list of morph target managers added to the scene
  23497. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23498. */
  23499. this.morphTargetManagers = new Array();
  23500. /**
  23501. * The list of geometries used in the scene.
  23502. */
  23503. this.geometries = new Array();
  23504. /**
  23505. * All of the tranform nodes added to this scene
  23506. * @see http://doc.babylonjs.com/how_to/transformnode
  23507. */
  23508. this.transformNodes = new Array();
  23509. /**
  23510. * ActionManagers available on the scene.
  23511. */
  23512. this.actionManagers = new Array();
  23513. /**
  23514. * Sounds to keep.
  23515. */
  23516. this.sounds = new Array();
  23517. /**
  23518. * Textures to keep.
  23519. */
  23520. this.textures = new Array();
  23521. }
  23522. /**
  23523. * Adds a parser in the list of available ones
  23524. * @param name Defines the name of the parser
  23525. * @param parser Defines the parser to add
  23526. */
  23527. AbstractScene.AddParser = function (name, parser) {
  23528. this._BabylonFileParsers[name] = parser;
  23529. };
  23530. /**
  23531. * Gets a general parser from the list of avaialble ones
  23532. * @param name Defines the name of the parser
  23533. * @returns the requested parser or null
  23534. */
  23535. AbstractScene.GetParser = function (name) {
  23536. if (this._BabylonFileParsers[name]) {
  23537. return this._BabylonFileParsers[name];
  23538. }
  23539. return null;
  23540. };
  23541. /**
  23542. * Adds n individual parser in the list of available ones
  23543. * @param name Defines the name of the parser
  23544. * @param parser Defines the parser to add
  23545. */
  23546. AbstractScene.AddIndividualParser = function (name, parser) {
  23547. this._IndividualBabylonFileParsers[name] = parser;
  23548. };
  23549. /**
  23550. * Gets an individual parser from the list of avaialble ones
  23551. * @param name Defines the name of the parser
  23552. * @returns the requested parser or null
  23553. */
  23554. AbstractScene.GetIndividualParser = function (name) {
  23555. if (this._IndividualBabylonFileParsers[name]) {
  23556. return this._IndividualBabylonFileParsers[name];
  23557. }
  23558. return null;
  23559. };
  23560. /**
  23561. * Parser json data and populate both a scene and its associated container object
  23562. * @param jsonData Defines the data to parse
  23563. * @param scene Defines the scene to parse the data for
  23564. * @param container Defines the container attached to the parsing sequence
  23565. * @param rootUrl Defines the root url of the data
  23566. */
  23567. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23568. for (var parserName in this._BabylonFileParsers) {
  23569. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23570. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23571. }
  23572. }
  23573. };
  23574. /**
  23575. * Stores the list of available parsers in the application.
  23576. */
  23577. AbstractScene._BabylonFileParsers = {};
  23578. /**
  23579. * Stores the list of available individual parsers in the application.
  23580. */
  23581. AbstractScene._IndividualBabylonFileParsers = {};
  23582. return AbstractScene;
  23583. }());
  23584. BABYLON.AbstractScene = AbstractScene;
  23585. })(BABYLON || (BABYLON = {}));
  23586. //# sourceMappingURL=babylon.abstractScene.js.map
  23587. var BABYLON;
  23588. (function (BABYLON) {
  23589. /** @hidden */
  23590. var ClickInfo = /** @class */ (function () {
  23591. function ClickInfo() {
  23592. this._singleClick = false;
  23593. this._doubleClick = false;
  23594. this._hasSwiped = false;
  23595. this._ignore = false;
  23596. }
  23597. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23598. get: function () {
  23599. return this._singleClick;
  23600. },
  23601. set: function (b) {
  23602. this._singleClick = b;
  23603. },
  23604. enumerable: true,
  23605. configurable: true
  23606. });
  23607. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23608. get: function () {
  23609. return this._doubleClick;
  23610. },
  23611. set: function (b) {
  23612. this._doubleClick = b;
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23618. get: function () {
  23619. return this._hasSwiped;
  23620. },
  23621. set: function (b) {
  23622. this._hasSwiped = b;
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23628. get: function () {
  23629. return this._ignore;
  23630. },
  23631. set: function (b) {
  23632. this._ignore = b;
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. return ClickInfo;
  23638. }());
  23639. /**
  23640. * This class is used by the onRenderingGroupObservable
  23641. */
  23642. var RenderingGroupInfo = /** @class */ (function () {
  23643. function RenderingGroupInfo() {
  23644. }
  23645. /**
  23646. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23647. * This stage will be fired no matter what
  23648. */
  23649. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23650. /**
  23651. * Called before opaque object are rendered.
  23652. * This stage will be fired only if there's 3D Opaque content to render
  23653. */
  23654. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23655. /**
  23656. * Called after the opaque objects are rendered and before the transparent ones
  23657. * This stage will be fired only if there's 3D transparent content to render
  23658. */
  23659. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23660. /**
  23661. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23662. * This stage will be fired no matter what
  23663. */
  23664. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23665. return RenderingGroupInfo;
  23666. }());
  23667. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23668. /**
  23669. * Represents a scene to be rendered by the engine.
  23670. * @see http://doc.babylonjs.com/features/scene
  23671. */
  23672. var Scene = /** @class */ (function (_super) {
  23673. __extends(Scene, _super);
  23674. /**
  23675. * Creates a new Scene
  23676. * @param engine defines the engine to use to render this scene
  23677. */
  23678. function Scene(engine) {
  23679. var _this = _super.call(this) || this;
  23680. // Members
  23681. /**
  23682. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23683. */
  23684. _this.autoClear = true;
  23685. /**
  23686. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23687. */
  23688. _this.autoClearDepthAndStencil = true;
  23689. /**
  23690. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23691. */
  23692. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23693. /**
  23694. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23695. */
  23696. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23697. _this._forceWireframe = false;
  23698. _this._forcePointsCloud = false;
  23699. /**
  23700. * Gets or sets a boolean indicating if animations are enabled
  23701. */
  23702. _this.animationsEnabled = true;
  23703. _this._animationPropertiesOverride = null;
  23704. /**
  23705. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23706. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23707. */
  23708. _this.useConstantAnimationDeltaTime = false;
  23709. /**
  23710. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23711. * Please note that it requires to run a ray cast through the scene on every frame
  23712. */
  23713. _this.constantlyUpdateMeshUnderPointer = false;
  23714. /**
  23715. * Defines the HTML cursor to use when hovering over interactive elements
  23716. */
  23717. _this.hoverCursor = "pointer";
  23718. /**
  23719. * Defines the HTML default cursor to use (empty by default)
  23720. */
  23721. _this.defaultCursor = "";
  23722. /**
  23723. * This is used to call preventDefault() on pointer down
  23724. * in order to block unwanted artifacts like system double clicks
  23725. */
  23726. _this.preventDefaultOnPointerDown = true;
  23727. // Metadata
  23728. /**
  23729. * Gets or sets user defined metadata
  23730. */
  23731. _this.metadata = null;
  23732. /**
  23733. * Use this array to add regular expressions used to disable offline support for specific urls
  23734. */
  23735. _this.disableOfflineSupportExceptionRules = new Array();
  23736. /**
  23737. * An event triggered when the scene is disposed.
  23738. */
  23739. _this.onDisposeObservable = new BABYLON.Observable();
  23740. _this._onDisposeObserver = null;
  23741. /**
  23742. * An event triggered before rendering the scene (right after animations and physics)
  23743. */
  23744. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23745. _this._onBeforeRenderObserver = null;
  23746. /**
  23747. * An event triggered after rendering the scene
  23748. */
  23749. _this.onAfterRenderObservable = new BABYLON.Observable();
  23750. _this._onAfterRenderObserver = null;
  23751. /**
  23752. * An event triggered before animating the scene
  23753. */
  23754. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered after animations processing
  23757. */
  23758. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23759. /**
  23760. * An event triggered before draw calls are ready to be sent
  23761. */
  23762. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23763. /**
  23764. * An event triggered after draw calls have been sent
  23765. */
  23766. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23767. /**
  23768. * An event triggered when physic simulation is about to be run
  23769. */
  23770. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23771. /**
  23772. * An event triggered when physic simulation has been done
  23773. */
  23774. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23775. /**
  23776. * An event triggered when the scene is ready
  23777. */
  23778. _this.onReadyObservable = new BABYLON.Observable();
  23779. /**
  23780. * An event triggered before rendering a camera
  23781. */
  23782. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23783. _this._onBeforeCameraRenderObserver = null;
  23784. /**
  23785. * An event triggered after rendering a camera
  23786. */
  23787. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23788. _this._onAfterCameraRenderObserver = null;
  23789. /**
  23790. * An event triggered when active meshes evaluation is about to start
  23791. */
  23792. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23793. /**
  23794. * An event triggered when active meshes evaluation is done
  23795. */
  23796. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23797. /**
  23798. * An event triggered when particles rendering is about to start
  23799. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23800. */
  23801. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered when particles rendering is done
  23804. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23805. */
  23806. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23807. /**
  23808. * An event triggered when sprites rendering is about to start
  23809. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23810. */
  23811. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered when sprites rendering is done
  23814. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23815. */
  23816. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23817. /**
  23818. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23819. */
  23820. _this.onDataLoadedObservable = new BABYLON.Observable();
  23821. /**
  23822. * An event triggered when a camera is created
  23823. */
  23824. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23825. /**
  23826. * An event triggered when a camera is removed
  23827. */
  23828. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23829. /**
  23830. * An event triggered when a light is created
  23831. */
  23832. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23833. /**
  23834. * An event triggered when a light is removed
  23835. */
  23836. _this.onLightRemovedObservable = new BABYLON.Observable();
  23837. /**
  23838. * An event triggered when a geometry is created
  23839. */
  23840. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23841. /**
  23842. * An event triggered when a geometry is removed
  23843. */
  23844. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23845. /**
  23846. * An event triggered when a transform node is created
  23847. */
  23848. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23849. /**
  23850. * An event triggered when a transform node is removed
  23851. */
  23852. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23853. /**
  23854. * An event triggered when a mesh is created
  23855. */
  23856. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23857. /**
  23858. * An event triggered when a mesh is removed
  23859. */
  23860. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23861. /**
  23862. * An event triggered when render targets are about to be rendered
  23863. * Can happen multiple times per frame.
  23864. */
  23865. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23866. /**
  23867. * An event triggered when render targets were rendered.
  23868. * Can happen multiple times per frame.
  23869. */
  23870. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23871. /**
  23872. * An event triggered before calculating deterministic simulation step
  23873. */
  23874. _this.onBeforeStepObservable = new BABYLON.Observable();
  23875. /**
  23876. * An event triggered after calculating deterministic simulation step
  23877. */
  23878. _this.onAfterStepObservable = new BABYLON.Observable();
  23879. /**
  23880. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23881. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23882. * 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)
  23883. */
  23884. _this.onRenderingGroupObservable = new BABYLON.Observable();
  23885. // Animations
  23886. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23887. /**
  23888. * 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).
  23889. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23890. */
  23891. _this.onPrePointerObservable = new BABYLON.Observable();
  23892. /**
  23893. * Observable event triggered each time an input event is received from the rendering canvas
  23894. */
  23895. _this.onPointerObservable = new BABYLON.Observable();
  23896. _this._meshPickProceed = false;
  23897. _this._currentPickResult = null;
  23898. _this._previousPickResult = null;
  23899. _this._totalPointersPressed = 0;
  23900. _this._doubleClickOccured = false;
  23901. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23902. _this.cameraToUseForPointers = null;
  23903. _this._pointerX = 0;
  23904. _this._pointerY = 0;
  23905. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23906. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23907. _this._startingPointerTime = 0;
  23908. _this._previousStartingPointerTime = 0;
  23909. _this._pointerCaptures = {};
  23910. // Deterministic lockstep
  23911. _this._timeAccumulator = 0;
  23912. _this._currentStepId = 0;
  23913. _this._currentInternalStep = 0;
  23914. // Keyboard
  23915. /**
  23916. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23917. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23918. */
  23919. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23920. /**
  23921. * Observable event triggered each time an keyboard event is received from the hosting window
  23922. */
  23923. _this.onKeyboardObservable = new BABYLON.Observable();
  23924. // Coordinates system
  23925. _this._useRightHandedSystem = false;
  23926. // Fog
  23927. _this._fogEnabled = true;
  23928. _this._fogMode = Scene.FOGMODE_NONE;
  23929. /**
  23930. * Gets or sets the fog color to use
  23931. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23932. */
  23933. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23934. /**
  23935. * Gets or sets the fog density to use
  23936. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23937. */
  23938. _this.fogDensity = 0.1;
  23939. /**
  23940. * Gets or sets the fog start distance to use
  23941. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23942. */
  23943. _this.fogStart = 0;
  23944. /**
  23945. * Gets or sets the fog end distance to use
  23946. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23947. */
  23948. _this.fogEnd = 1000.0;
  23949. // Lights
  23950. _this._shadowsEnabled = true;
  23951. _this._lightsEnabled = true;
  23952. /** All of the active cameras added to this scene. */
  23953. _this.activeCameras = new Array();
  23954. // Textures
  23955. _this._texturesEnabled = true;
  23956. // Particles
  23957. /**
  23958. * Gets or sets a boolean indicating if particles are enabled on this scene
  23959. */
  23960. _this.particlesEnabled = true;
  23961. // Sprites
  23962. /**
  23963. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23964. */
  23965. _this.spritesEnabled = true;
  23966. /**
  23967. * All of the sprite managers added to this scene
  23968. * @see http://doc.babylonjs.com/babylon101/sprites
  23969. */
  23970. _this.spriteManagers = new Array();
  23971. // Skeletons
  23972. _this._skeletonsEnabled = true;
  23973. // Lens flares
  23974. /**
  23975. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23976. */
  23977. _this.lensFlaresEnabled = true;
  23978. // Collisions
  23979. /**
  23980. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23981. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23982. */
  23983. _this.collisionsEnabled = true;
  23984. /**
  23985. * Defines the gravity applied to this scene (used only for collisions)
  23986. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23987. */
  23988. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23989. // Postprocesses
  23990. /**
  23991. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23992. */
  23993. _this.postProcessesEnabled = true;
  23994. /**
  23995. * The list of postprocesses added to the scene
  23996. */
  23997. _this.postProcesses = new Array();
  23998. // Customs render targets
  23999. /**
  24000. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24001. */
  24002. _this.renderTargetsEnabled = true;
  24003. /**
  24004. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24005. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24006. */
  24007. _this.dumpNextRenderTargets = false;
  24008. /**
  24009. * The list of user defined render targets added to the scene
  24010. */
  24011. _this.customRenderTargets = new Array();
  24012. /**
  24013. * Gets the list of meshes imported to the scene through SceneLoader
  24014. */
  24015. _this.importedMeshesFiles = new Array();
  24016. // Probes
  24017. /**
  24018. * Gets or sets a boolean indicating if probes are enabled on this scene
  24019. */
  24020. _this.probesEnabled = true;
  24021. /**
  24022. * The list of reflection probes added to the scene
  24023. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24024. */
  24025. _this.reflectionProbes = new Array();
  24026. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24027. // Procedural textures
  24028. /**
  24029. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24030. */
  24031. _this.proceduralTexturesEnabled = true;
  24032. /**
  24033. * The list of procedural textures added to the scene
  24034. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24035. */
  24036. _this.proceduralTextures = new Array();
  24037. /**
  24038. * The list of sound tracks added to the scene
  24039. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24040. */
  24041. _this.soundTracks = new Array();
  24042. _this._audioEnabled = true;
  24043. _this._headphone = false;
  24044. // Performance counters
  24045. _this._totalVertices = new BABYLON.PerfCounter();
  24046. /** @hidden */
  24047. _this._activeIndices = new BABYLON.PerfCounter();
  24048. /** @hidden */
  24049. _this._activeParticles = new BABYLON.PerfCounter();
  24050. /** @hidden */
  24051. _this._activeBones = new BABYLON.PerfCounter();
  24052. _this._animationTime = 0;
  24053. /**
  24054. * Gets or sets a general scale for animation speed
  24055. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24056. */
  24057. _this.animationTimeScale = 1;
  24058. _this._renderId = 0;
  24059. _this._executeWhenReadyTimeoutId = -1;
  24060. _this._intermediateRendering = false;
  24061. _this._viewUpdateFlag = -1;
  24062. _this._projectionUpdateFlag = -1;
  24063. _this._alternateViewUpdateFlag = -1;
  24064. _this._alternateProjectionUpdateFlag = -1;
  24065. /** @hidden */
  24066. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24067. _this._activeRequests = new Array();
  24068. _this._pendingData = new Array();
  24069. _this._isDisposed = false;
  24070. /**
  24071. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24072. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24073. */
  24074. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24075. _this._activeMeshes = new BABYLON.SmartArray(256);
  24076. _this._processedMaterials = new BABYLON.SmartArray(256);
  24077. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24078. /** @hidden */
  24079. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24080. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24081. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24082. /** @hidden */
  24083. _this._activeAnimatables = new Array();
  24084. _this._transformMatrix = BABYLON.Matrix.Zero();
  24085. _this._useAlternateCameraConfiguration = false;
  24086. _this._alternateRendering = false;
  24087. /**
  24088. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24089. * This is useful if there are more lights that the maximum simulteanous authorized
  24090. */
  24091. _this.requireLightSorting = false;
  24092. _this._depthRenderer = {};
  24093. /**
  24094. * Backing store of defined scene components.
  24095. */
  24096. _this._components = [];
  24097. /**
  24098. * Backing store of defined scene components.
  24099. */
  24100. _this._serializableComponents = [];
  24101. /**
  24102. * List of components to register on the next registration step.
  24103. */
  24104. _this._transientComponents = [];
  24105. /**
  24106. * Defines the actions happening before camera updates.
  24107. */
  24108. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24109. /**
  24110. * Defines the actions happening during the per mesh ready checks.
  24111. */
  24112. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24113. /**
  24114. * Defines the actions happening before evaluate active mesh checks.
  24115. */
  24116. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24117. /**
  24118. * Defines the actions happening during the evaluate sub mesh checks.
  24119. */
  24120. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24121. /**
  24122. * Defines the actions happening during the active mesh stage.
  24123. */
  24124. _this._activeMeshStage = BABYLON.Stage.Create();
  24125. /**
  24126. * Defines the actions happening during the per camera render target step.
  24127. */
  24128. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24129. /**
  24130. * Defines the actions happening just before the active camera is drawing.
  24131. */
  24132. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24133. /**
  24134. * Defines the actions happening just before a rendering group is drawing.
  24135. */
  24136. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24137. /**
  24138. * Defines the actions happening just after a rendering group has been drawn.
  24139. */
  24140. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24141. /**
  24142. * Defines the actions happening just after the active camera has been drawn.
  24143. */
  24144. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24145. _this._activeMeshesFrozen = false;
  24146. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24147. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24148. _this._engine.scenes.push(_this);
  24149. _this._uid = null;
  24150. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24151. if (BABYLON.PostProcessManager) {
  24152. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24153. }
  24154. if (BABYLON.OutlineRenderer) {
  24155. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24156. }
  24157. if (BABYLON.Tools.IsWindowObjectExist()) {
  24158. _this.attachControl();
  24159. }
  24160. //simplification queue
  24161. if (BABYLON.SimplificationQueue) {
  24162. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24163. }
  24164. //collision coordinator initialization. For now legacy per default.
  24165. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24166. // Uniform Buffer
  24167. _this._createUbo();
  24168. // Default Image processing definition
  24169. if (BABYLON.ImageProcessingConfiguration) {
  24170. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24171. }
  24172. return _this;
  24173. }
  24174. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24175. /** The fog is deactivated */
  24176. get: function () {
  24177. return Scene._FOGMODE_NONE;
  24178. },
  24179. enumerable: true,
  24180. configurable: true
  24181. });
  24182. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24183. /** The fog density is following an exponential function */
  24184. get: function () {
  24185. return Scene._FOGMODE_EXP;
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24191. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24192. get: function () {
  24193. return Scene._FOGMODE_EXP2;
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24199. /** The fog density is following a linear function. */
  24200. get: function () {
  24201. return Scene._FOGMODE_LINEAR;
  24202. },
  24203. enumerable: true,
  24204. configurable: true
  24205. });
  24206. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24207. /**
  24208. * Texture used in all pbr material as the reflection texture.
  24209. * As in the majority of the scene they are the same (exception for multi room and so on),
  24210. * this is easier to reference from here than from all the materials.
  24211. */
  24212. get: function () {
  24213. return this._environmentTexture;
  24214. },
  24215. /**
  24216. * Texture used in all pbr material as the reflection texture.
  24217. * As in the majority of the scene they are the same (exception for multi room and so on),
  24218. * this is easier to set here than in all the materials.
  24219. */
  24220. set: function (value) {
  24221. if (this._environmentTexture === value) {
  24222. return;
  24223. }
  24224. this._environmentTexture = value;
  24225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24226. },
  24227. enumerable: true,
  24228. configurable: true
  24229. });
  24230. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24231. /**
  24232. * Default image processing configuration used either in the rendering
  24233. * Forward main pass or through the imageProcessingPostProcess if present.
  24234. * As in the majority of the scene they are the same (exception for multi camera),
  24235. * this is easier to reference from here than from all the materials and post process.
  24236. *
  24237. * No setter as we it is a shared configuration, you can set the values instead.
  24238. */
  24239. get: function () {
  24240. return this._imageProcessingConfiguration;
  24241. },
  24242. enumerable: true,
  24243. configurable: true
  24244. });
  24245. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24246. get: function () {
  24247. return this._forceWireframe;
  24248. },
  24249. /**
  24250. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24251. */
  24252. set: function (value) {
  24253. if (this._forceWireframe === value) {
  24254. return;
  24255. }
  24256. this._forceWireframe = value;
  24257. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24263. get: function () {
  24264. return this._forcePointsCloud;
  24265. },
  24266. /**
  24267. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24268. */
  24269. set: function (value) {
  24270. if (this._forcePointsCloud === value) {
  24271. return;
  24272. }
  24273. this._forcePointsCloud = value;
  24274. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24275. },
  24276. enumerable: true,
  24277. configurable: true
  24278. });
  24279. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24280. /**
  24281. * Gets or sets the animation properties override
  24282. */
  24283. get: function () {
  24284. return this._animationPropertiesOverride;
  24285. },
  24286. set: function (value) {
  24287. this._animationPropertiesOverride = value;
  24288. },
  24289. enumerable: true,
  24290. configurable: true
  24291. });
  24292. Object.defineProperty(Scene.prototype, "onDispose", {
  24293. /** Sets a function to be executed when this scene is disposed. */
  24294. set: function (callback) {
  24295. if (this._onDisposeObserver) {
  24296. this.onDisposeObservable.remove(this._onDisposeObserver);
  24297. }
  24298. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24299. },
  24300. enumerable: true,
  24301. configurable: true
  24302. });
  24303. Object.defineProperty(Scene.prototype, "beforeRender", {
  24304. /** Sets a function to be executed before rendering this scene */
  24305. set: function (callback) {
  24306. if (this._onBeforeRenderObserver) {
  24307. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24308. }
  24309. if (callback) {
  24310. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24311. }
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Object.defineProperty(Scene.prototype, "afterRender", {
  24317. /** Sets a function to be executed after rendering this scene */
  24318. set: function (callback) {
  24319. if (this._onAfterRenderObserver) {
  24320. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24321. }
  24322. if (callback) {
  24323. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24324. }
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24330. /** Sets a function to be executed before rendering a camera*/
  24331. set: function (callback) {
  24332. if (this._onBeforeCameraRenderObserver) {
  24333. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24334. }
  24335. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24336. },
  24337. enumerable: true,
  24338. configurable: true
  24339. });
  24340. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24341. /** Sets a function to be executed after rendering a camera*/
  24342. set: function (callback) {
  24343. if (this._onAfterCameraRenderObserver) {
  24344. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24345. }
  24346. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24352. /**
  24353. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24354. */
  24355. get: function () {
  24356. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24362. get: function () {
  24363. return this._useRightHandedSystem;
  24364. },
  24365. /**
  24366. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24367. */
  24368. set: function (value) {
  24369. if (this._useRightHandedSystem === value) {
  24370. return;
  24371. }
  24372. this._useRightHandedSystem = value;
  24373. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24374. },
  24375. enumerable: true,
  24376. configurable: true
  24377. });
  24378. /**
  24379. * Sets the step Id used by deterministic lock step
  24380. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24381. * @param newStepId defines the step Id
  24382. */
  24383. Scene.prototype.setStepId = function (newStepId) {
  24384. this._currentStepId = newStepId;
  24385. };
  24386. ;
  24387. /**
  24388. * Gets the step Id used by deterministic lock step
  24389. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24390. * @returns the step Id
  24391. */
  24392. Scene.prototype.getStepId = function () {
  24393. return this._currentStepId;
  24394. };
  24395. ;
  24396. /**
  24397. * Gets the internal step used by deterministic lock step
  24398. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24399. * @returns the internal step
  24400. */
  24401. Scene.prototype.getInternalStep = function () {
  24402. return this._currentInternalStep;
  24403. };
  24404. ;
  24405. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24406. get: function () {
  24407. return this._fogEnabled;
  24408. },
  24409. /**
  24410. * Gets or sets a boolean indicating if fog is enabled on this scene
  24411. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24412. */
  24413. set: function (value) {
  24414. if (this._fogEnabled === value) {
  24415. return;
  24416. }
  24417. this._fogEnabled = value;
  24418. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24419. },
  24420. enumerable: true,
  24421. configurable: true
  24422. });
  24423. Object.defineProperty(Scene.prototype, "fogMode", {
  24424. get: function () {
  24425. return this._fogMode;
  24426. },
  24427. /**
  24428. * Gets or sets the fog mode to use
  24429. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24430. */
  24431. set: function (value) {
  24432. if (this._fogMode === value) {
  24433. return;
  24434. }
  24435. this._fogMode = value;
  24436. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24442. get: function () {
  24443. return this._shadowsEnabled;
  24444. },
  24445. /**
  24446. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24447. */
  24448. set: function (value) {
  24449. if (this._shadowsEnabled === value) {
  24450. return;
  24451. }
  24452. this._shadowsEnabled = value;
  24453. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24459. get: function () {
  24460. return this._lightsEnabled;
  24461. },
  24462. /**
  24463. * Gets or sets a boolean indicating if lights are enabled on this scene
  24464. */
  24465. set: function (value) {
  24466. if (this._lightsEnabled === value) {
  24467. return;
  24468. }
  24469. this._lightsEnabled = value;
  24470. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24476. /** The default material used on meshes when no material is affected */
  24477. get: function () {
  24478. if (!this._defaultMaterial) {
  24479. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24480. }
  24481. return this._defaultMaterial;
  24482. },
  24483. /** The default material used on meshes when no material is affected */
  24484. set: function (value) {
  24485. this._defaultMaterial = value;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24491. get: function () {
  24492. return this._texturesEnabled;
  24493. },
  24494. /**
  24495. * Gets or sets a boolean indicating if textures are enabled on this scene
  24496. */
  24497. set: function (value) {
  24498. if (this._texturesEnabled === value) {
  24499. return;
  24500. }
  24501. this._texturesEnabled = value;
  24502. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24508. get: function () {
  24509. return this._skeletonsEnabled;
  24510. },
  24511. /**
  24512. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24513. */
  24514. set: function (value) {
  24515. if (this._skeletonsEnabled === value) {
  24516. return;
  24517. }
  24518. this._skeletonsEnabled = value;
  24519. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24525. /**
  24526. * Gets the postprocess render pipeline manager
  24527. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24528. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24529. */
  24530. get: function () {
  24531. if (!this._postProcessRenderPipelineManager) {
  24532. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24533. }
  24534. return this._postProcessRenderPipelineManager;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24540. /**
  24541. * Gets the main soundtrack associated with the scene
  24542. */
  24543. get: function () {
  24544. if (!this._mainSoundTrack) {
  24545. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24546. }
  24547. return this._mainSoundTrack;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24553. /** @hidden */
  24554. get: function () {
  24555. return this._alternateRendering;
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24561. /**
  24562. * Gets the list of frustum planes (built from the active camera)
  24563. */
  24564. get: function () {
  24565. return this._frustumPlanes;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24571. /**
  24572. * Gets the current geometry buffer associated to the scene.
  24573. */
  24574. get: function () {
  24575. return this._geometryBufferRenderer;
  24576. },
  24577. /**
  24578. * Sets the current geometry buffer for the scene.
  24579. */
  24580. set: function (geometryBufferRenderer) {
  24581. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24582. this._geometryBufferRenderer = geometryBufferRenderer;
  24583. }
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. /**
  24589. * Registers the transient components if needed.
  24590. */
  24591. Scene.prototype._registerTransientComponents = function () {
  24592. // Register components that have been associated lately to the scene.
  24593. if (this._transientComponents.length > 0) {
  24594. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24595. var component = _a[_i];
  24596. component.register();
  24597. }
  24598. this._transientComponents = [];
  24599. }
  24600. };
  24601. /**
  24602. * Add a component to the scene.
  24603. * Note that the ccomponent could be registered on th next frame if this is called after
  24604. * the register component stage.
  24605. * @param component Defines the component to add to the scene
  24606. */
  24607. Scene.prototype._addComponent = function (component) {
  24608. this._components.push(component);
  24609. this._transientComponents.push(component);
  24610. var serializableComponent = component;
  24611. if (serializableComponent.addFromContainer) {
  24612. this._serializableComponents.push(serializableComponent);
  24613. }
  24614. };
  24615. /**
  24616. * Gets a component from the scene.
  24617. * @param name defines the name of the component to retrieve
  24618. * @returns the component or null if not present
  24619. */
  24620. Scene.prototype._getComponent = function (name) {
  24621. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24622. var component = _a[_i];
  24623. if (component.name === name) {
  24624. return component;
  24625. }
  24626. }
  24627. return null;
  24628. };
  24629. Object.defineProperty(Scene.prototype, "debugLayer", {
  24630. /**
  24631. * Gets the debug layer (aka Inspector) associated with the scene
  24632. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24633. */
  24634. get: function () {
  24635. if (!this._debugLayer) {
  24636. this._debugLayer = new BABYLON.DebugLayer(this);
  24637. }
  24638. return this._debugLayer;
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24644. /**
  24645. * Gets a boolean indicating if collisions are processed on a web worker
  24646. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24647. */
  24648. get: function () {
  24649. return this._workerCollisions;
  24650. },
  24651. set: function (enabled) {
  24652. if (!BABYLON.CollisionCoordinatorLegacy) {
  24653. return;
  24654. }
  24655. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24656. this._workerCollisions = enabled;
  24657. if (this.collisionCoordinator) {
  24658. this.collisionCoordinator.destroy();
  24659. }
  24660. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24661. this.collisionCoordinator.init(this);
  24662. },
  24663. enumerable: true,
  24664. configurable: true
  24665. });
  24666. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24667. /**
  24668. * Gets the octree used to boost mesh selection (picking)
  24669. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24670. */
  24671. get: function () {
  24672. return this._selectionOctree;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24678. /**
  24679. * Gets the mesh that is currently under the pointer
  24680. */
  24681. get: function () {
  24682. return this._pointerOverMesh;
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. Object.defineProperty(Scene.prototype, "pointerX", {
  24688. /**
  24689. * Gets the current on-screen X position of the pointer
  24690. */
  24691. get: function () {
  24692. return this._pointerX;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. Object.defineProperty(Scene.prototype, "pointerY", {
  24698. /**
  24699. * Gets the current on-screen Y position of the pointer
  24700. */
  24701. get: function () {
  24702. return this._pointerY;
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. /**
  24708. * Gets the cached material (ie. the latest rendered one)
  24709. * @returns the cached material
  24710. */
  24711. Scene.prototype.getCachedMaterial = function () {
  24712. return this._cachedMaterial;
  24713. };
  24714. /**
  24715. * Gets the cached effect (ie. the latest rendered one)
  24716. * @returns the cached effect
  24717. */
  24718. Scene.prototype.getCachedEffect = function () {
  24719. return this._cachedEffect;
  24720. };
  24721. /**
  24722. * Gets the cached visibility state (ie. the latest rendered one)
  24723. * @returns the cached visibility state
  24724. */
  24725. Scene.prototype.getCachedVisibility = function () {
  24726. return this._cachedVisibility;
  24727. };
  24728. /**
  24729. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24730. * @param material defines the current material
  24731. * @param effect defines the current effect
  24732. * @param visibility defines the current visibility state
  24733. * @returns true if one parameter is not cached
  24734. */
  24735. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24736. if (visibility === void 0) { visibility = 1; }
  24737. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24738. };
  24739. /**
  24740. * Gets the outline renderer associated with the scene
  24741. * @returns a OutlineRenderer
  24742. */
  24743. Scene.prototype.getOutlineRenderer = function () {
  24744. return this._outlineRenderer;
  24745. };
  24746. /**
  24747. * Gets the engine associated with the scene
  24748. * @returns an Engine
  24749. */
  24750. Scene.prototype.getEngine = function () {
  24751. return this._engine;
  24752. };
  24753. /**
  24754. * Gets the total number of vertices rendered per frame
  24755. * @returns the total number of vertices rendered per frame
  24756. */
  24757. Scene.prototype.getTotalVertices = function () {
  24758. return this._totalVertices.current;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24761. /**
  24762. * Gets the performance counter for total vertices
  24763. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24764. */
  24765. get: function () {
  24766. return this._totalVertices;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. /**
  24772. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24773. * @returns the total number of active indices rendered per frame
  24774. */
  24775. Scene.prototype.getActiveIndices = function () {
  24776. return this._activeIndices.current;
  24777. };
  24778. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24779. /**
  24780. * Gets the performance counter for active indices
  24781. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24782. */
  24783. get: function () {
  24784. return this._activeIndices;
  24785. },
  24786. enumerable: true,
  24787. configurable: true
  24788. });
  24789. /**
  24790. * Gets the total number of active particles rendered per frame
  24791. * @returns the total number of active particles rendered per frame
  24792. */
  24793. Scene.prototype.getActiveParticles = function () {
  24794. return this._activeParticles.current;
  24795. };
  24796. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24797. /**
  24798. * Gets the performance counter for active particles
  24799. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24800. */
  24801. get: function () {
  24802. return this._activeParticles;
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. /**
  24808. * Gets the total number of active bones rendered per frame
  24809. * @returns the total number of active bones rendered per frame
  24810. */
  24811. Scene.prototype.getActiveBones = function () {
  24812. return this._activeBones.current;
  24813. };
  24814. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24815. /**
  24816. * Gets the performance counter for active bones
  24817. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24818. */
  24819. get: function () {
  24820. return this._activeBones;
  24821. },
  24822. enumerable: true,
  24823. configurable: true
  24824. });
  24825. /** @hidden */
  24826. Scene.prototype.getInterFramePerfCounter = function () {
  24827. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24828. return 0;
  24829. };
  24830. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24831. /** @hidden */
  24832. get: function () {
  24833. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24834. return null;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. /** @hidden */
  24840. Scene.prototype.getLastFrameDuration = function () {
  24841. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24842. return 0;
  24843. };
  24844. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24845. /** @hidden */
  24846. get: function () {
  24847. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24848. return null;
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. /** @hidden */
  24854. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24855. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24856. return 0;
  24857. };
  24858. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24859. /** @hidden */
  24860. get: function () {
  24861. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24862. return null;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. /**
  24868. * Gets the array of active meshes
  24869. * @returns an array of AbstractMesh
  24870. */
  24871. Scene.prototype.getActiveMeshes = function () {
  24872. return this._activeMeshes;
  24873. };
  24874. /** @hidden */
  24875. Scene.prototype.getRenderTargetsDuration = function () {
  24876. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24877. return 0;
  24878. };
  24879. /** @hidden */
  24880. Scene.prototype.getRenderDuration = function () {
  24881. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24882. return 0;
  24883. };
  24884. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24885. /** @hidden */
  24886. get: function () {
  24887. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24888. return null;
  24889. },
  24890. enumerable: true,
  24891. configurable: true
  24892. });
  24893. /** @hidden */
  24894. Scene.prototype.getParticlesDuration = function () {
  24895. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24896. return 0;
  24897. };
  24898. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24899. /** @hidden */
  24900. get: function () {
  24901. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24902. return null;
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. /** @hidden */
  24908. Scene.prototype.getSpritesDuration = function () {
  24909. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24910. return 0;
  24911. };
  24912. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24913. /** @hidden */
  24914. get: function () {
  24915. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24916. return null;
  24917. },
  24918. enumerable: true,
  24919. configurable: true
  24920. });
  24921. /**
  24922. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24923. * @returns a number
  24924. */
  24925. Scene.prototype.getAnimationRatio = function () {
  24926. return this._animationRatio;
  24927. };
  24928. /**
  24929. * Gets an unique Id for the current frame
  24930. * @returns a number
  24931. */
  24932. Scene.prototype.getRenderId = function () {
  24933. return this._renderId;
  24934. };
  24935. /** Call this function if you want to manually increment the render Id*/
  24936. Scene.prototype.incrementRenderId = function () {
  24937. this._renderId++;
  24938. };
  24939. Scene.prototype._updatePointerPosition = function (evt) {
  24940. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24941. if (!canvasRect) {
  24942. return;
  24943. }
  24944. this._pointerX = evt.clientX - canvasRect.left;
  24945. this._pointerY = evt.clientY - canvasRect.top;
  24946. this._unTranslatedPointerX = this._pointerX;
  24947. this._unTranslatedPointerY = this._pointerY;
  24948. };
  24949. Scene.prototype._createUbo = function () {
  24950. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24951. this._sceneUbo.addUniform("viewProjection", 16);
  24952. this._sceneUbo.addUniform("view", 16);
  24953. };
  24954. Scene.prototype._createAlternateUbo = function () {
  24955. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24956. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24957. this._alternateSceneUbo.addUniform("view", 16);
  24958. };
  24959. // Pointers handling
  24960. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24961. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24962. if (result) {
  24963. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24964. }
  24965. return result;
  24966. };
  24967. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24968. if (pointerInfo.pickInfo) {
  24969. if (!pointerInfo.pickInfo.ray) {
  24970. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24971. }
  24972. }
  24973. };
  24974. /**
  24975. * Use this method to simulate a pointer move on a mesh
  24976. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24977. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24978. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24979. * @returns the current scene
  24980. */
  24981. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24982. var evt = new PointerEvent("pointermove", pointerEventInit);
  24983. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24984. return this;
  24985. }
  24986. return this._processPointerMove(pickResult, evt);
  24987. };
  24988. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24989. var canvas = this._engine.getRenderingCanvas();
  24990. if (!canvas) {
  24991. return this;
  24992. }
  24993. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24994. this.setPointerOverSprite(null);
  24995. this.setPointerOverMesh(pickResult.pickedMesh);
  24996. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24997. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24998. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24999. }
  25000. else {
  25001. canvas.style.cursor = this.hoverCursor;
  25002. }
  25003. }
  25004. else {
  25005. canvas.style.cursor = this.defaultCursor;
  25006. }
  25007. }
  25008. else {
  25009. this.setPointerOverMesh(null);
  25010. // Sprites
  25011. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25012. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25013. this.setPointerOverSprite(pickResult.pickedSprite);
  25014. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25015. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25016. }
  25017. else {
  25018. canvas.style.cursor = this.hoverCursor;
  25019. }
  25020. }
  25021. else {
  25022. this.setPointerOverSprite(null);
  25023. // Restore pointer
  25024. canvas.style.cursor = this.defaultCursor;
  25025. }
  25026. }
  25027. if (pickResult) {
  25028. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25029. if (this.onPointerMove) {
  25030. this.onPointerMove(evt, pickResult, type);
  25031. }
  25032. if (this.onPointerObservable.hasObservers()) {
  25033. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25034. this._setRayOnPointerInfo(pi);
  25035. this.onPointerObservable.notifyObservers(pi, type);
  25036. }
  25037. }
  25038. return this;
  25039. };
  25040. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25041. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25042. if (pickResult) {
  25043. pi.ray = pickResult.ray;
  25044. }
  25045. this.onPrePointerObservable.notifyObservers(pi, type);
  25046. if (pi.skipOnPointerObservable) {
  25047. return true;
  25048. }
  25049. else {
  25050. return false;
  25051. }
  25052. };
  25053. /**
  25054. * Use this method to simulate a pointer down on a mesh
  25055. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25056. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25057. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25058. * @returns the current scene
  25059. */
  25060. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25061. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25062. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25063. return this;
  25064. }
  25065. return this._processPointerDown(pickResult, evt);
  25066. };
  25067. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25068. var _this = this;
  25069. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25070. this._pickedDownMesh = pickResult.pickedMesh;
  25071. var actionManager = pickResult.pickedMesh.actionManager;
  25072. if (actionManager) {
  25073. if (actionManager.hasPickTriggers) {
  25074. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25075. switch (evt.button) {
  25076. case 0:
  25077. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25078. break;
  25079. case 1:
  25080. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25081. break;
  25082. case 2:
  25083. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25084. break;
  25085. }
  25086. }
  25087. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25088. window.setTimeout(function () {
  25089. 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);
  25090. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25091. if (_this._totalPointersPressed !== 0 &&
  25092. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25093. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25094. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25095. _this._startingPointerTime = 0;
  25096. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25097. }
  25098. }
  25099. }, Scene.LongPressDelay);
  25100. }
  25101. }
  25102. }
  25103. if (pickResult) {
  25104. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25105. if (this.onPointerDown) {
  25106. this.onPointerDown(evt, pickResult, type);
  25107. }
  25108. if (this.onPointerObservable.hasObservers()) {
  25109. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25110. this._setRayOnPointerInfo(pi);
  25111. this.onPointerObservable.notifyObservers(pi, type);
  25112. }
  25113. }
  25114. return this;
  25115. };
  25116. /**
  25117. * Use this method to simulate a pointer up on a mesh
  25118. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25119. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25120. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25121. * @returns the current scene
  25122. */
  25123. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25124. var evt = new PointerEvent("pointerup", pointerEventInit);
  25125. var clickInfo = new ClickInfo();
  25126. clickInfo.singleClick = true;
  25127. clickInfo.ignore = true;
  25128. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25129. return this;
  25130. }
  25131. return this._processPointerUp(pickResult, evt, clickInfo);
  25132. };
  25133. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25134. if (pickResult && pickResult && pickResult.pickedMesh) {
  25135. this._pickedUpMesh = pickResult.pickedMesh;
  25136. if (this._pickedDownMesh === this._pickedUpMesh) {
  25137. if (this.onPointerPick) {
  25138. this.onPointerPick(evt, pickResult);
  25139. }
  25140. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25141. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25142. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25143. this._setRayOnPointerInfo(pi);
  25144. this.onPointerObservable.notifyObservers(pi, type_1);
  25145. }
  25146. }
  25147. if (pickResult.pickedMesh.actionManager) {
  25148. if (clickInfo.ignore) {
  25149. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25150. }
  25151. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25152. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25153. }
  25154. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25155. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25156. }
  25157. }
  25158. }
  25159. if (this._pickedDownMesh &&
  25160. this._pickedDownMesh.actionManager &&
  25161. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25162. this._pickedDownMesh !== this._pickedUpMesh) {
  25163. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25164. }
  25165. var type = BABYLON.PointerEventTypes.POINTERUP;
  25166. if (this.onPointerObservable.hasObservers()) {
  25167. if (!clickInfo.ignore) {
  25168. if (!clickInfo.hasSwiped) {
  25169. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25170. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25171. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25172. this._setRayOnPointerInfo(pi);
  25173. this.onPointerObservable.notifyObservers(pi, type_2);
  25174. }
  25175. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25176. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25177. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25178. this._setRayOnPointerInfo(pi);
  25179. this.onPointerObservable.notifyObservers(pi, type_3);
  25180. }
  25181. }
  25182. }
  25183. else {
  25184. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25185. this._setRayOnPointerInfo(pi);
  25186. this.onPointerObservable.notifyObservers(pi, type);
  25187. }
  25188. }
  25189. if (this.onPointerUp) {
  25190. this.onPointerUp(evt, pickResult, type);
  25191. }
  25192. return this;
  25193. };
  25194. /**
  25195. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25196. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25197. * @returns true if the pointer was captured
  25198. */
  25199. Scene.prototype.isPointerCaptured = function (pointerId) {
  25200. if (pointerId === void 0) { pointerId = 0; }
  25201. return this._pointerCaptures[pointerId];
  25202. };
  25203. /**
  25204. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25205. * @param attachUp defines if you want to attach events to pointerup
  25206. * @param attachDown defines if you want to attach events to pointerdown
  25207. * @param attachMove defines if you want to attach events to pointermove
  25208. */
  25209. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25210. var _this = this;
  25211. if (attachUp === void 0) { attachUp = true; }
  25212. if (attachDown === void 0) { attachDown = true; }
  25213. if (attachMove === void 0) { attachMove = true; }
  25214. this._initActionManager = function (act, clickInfo) {
  25215. if (!_this._meshPickProceed) {
  25216. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25217. _this._currentPickResult = pickResult;
  25218. if (pickResult) {
  25219. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25220. }
  25221. _this._meshPickProceed = true;
  25222. }
  25223. return act;
  25224. };
  25225. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25226. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25227. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25228. btn !== _this._previousButtonPressed) {
  25229. _this._doubleClickOccured = false;
  25230. clickInfo.singleClick = true;
  25231. clickInfo.ignore = false;
  25232. cb(clickInfo, _this._currentPickResult);
  25233. }
  25234. };
  25235. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25236. var clickInfo = new ClickInfo();
  25237. _this._currentPickResult = null;
  25238. var act = null;
  25239. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25240. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25241. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25242. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25243. act = _this._initActionManager(act, clickInfo);
  25244. if (act)
  25245. checkPicking = act.hasPickTriggers;
  25246. }
  25247. if (checkPicking) {
  25248. var btn = evt.button;
  25249. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25250. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25251. if (!clickInfo.hasSwiped) {
  25252. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25253. if (!checkSingleClickImmediately) {
  25254. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25255. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25256. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25257. act = _this._initActionManager(act, clickInfo);
  25258. if (act)
  25259. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25260. }
  25261. }
  25262. if (checkSingleClickImmediately) {
  25263. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25264. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25265. btn !== _this._previousButtonPressed) {
  25266. clickInfo.singleClick = true;
  25267. cb(clickInfo, _this._currentPickResult);
  25268. }
  25269. }
  25270. // at least one double click is required to be check and exclusive double click is enabled
  25271. else {
  25272. // wait that no double click has been raised during the double click delay
  25273. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25274. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25275. }
  25276. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25277. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25278. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25279. act = _this._initActionManager(act, clickInfo);
  25280. if (act)
  25281. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25282. }
  25283. if (checkDoubleClick) {
  25284. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25285. if (btn === _this._previousButtonPressed &&
  25286. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25287. !_this._doubleClickOccured) {
  25288. // pointer has not moved for 2 clicks, it's a double click
  25289. if (!clickInfo.hasSwiped &&
  25290. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25291. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25292. _this._previousStartingPointerTime = 0;
  25293. _this._doubleClickOccured = true;
  25294. clickInfo.doubleClick = true;
  25295. clickInfo.ignore = false;
  25296. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25297. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25298. }
  25299. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25300. cb(clickInfo, _this._currentPickResult);
  25301. }
  25302. // if the two successive clicks are too far, it's just two simple clicks
  25303. else {
  25304. _this._doubleClickOccured = false;
  25305. _this._previousStartingPointerTime = _this._startingPointerTime;
  25306. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25307. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25308. _this._previousButtonPressed = btn;
  25309. if (Scene.ExclusiveDoubleClickMode) {
  25310. if (_this._previousDelayedSimpleClickTimeout) {
  25311. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25312. }
  25313. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25314. cb(clickInfo, _this._previousPickResult);
  25315. }
  25316. else {
  25317. cb(clickInfo, _this._currentPickResult);
  25318. }
  25319. }
  25320. }
  25321. // just the first click of the double has been raised
  25322. else {
  25323. _this._doubleClickOccured = false;
  25324. _this._previousStartingPointerTime = _this._startingPointerTime;
  25325. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25326. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25327. _this._previousButtonPressed = btn;
  25328. }
  25329. }
  25330. }
  25331. }
  25332. clickInfo.ignore = true;
  25333. cb(clickInfo, _this._currentPickResult);
  25334. };
  25335. this._spritePredicate = function (sprite) {
  25336. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25337. };
  25338. this._onPointerMove = function (evt) {
  25339. _this._updatePointerPosition(evt);
  25340. // PreObservable support
  25341. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25342. return;
  25343. }
  25344. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25345. return;
  25346. }
  25347. if (!_this.pointerMovePredicate) {
  25348. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25349. }
  25350. // Meshes
  25351. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25352. _this._processPointerMove(pickResult, evt);
  25353. };
  25354. this._onPointerDown = function (evt) {
  25355. _this._totalPointersPressed++;
  25356. _this._pickedDownMesh = null;
  25357. _this._meshPickProceed = false;
  25358. _this._updatePointerPosition(evt);
  25359. if (_this.preventDefaultOnPointerDown && canvas) {
  25360. evt.preventDefault();
  25361. canvas.focus();
  25362. }
  25363. // PreObservable support
  25364. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25365. return;
  25366. }
  25367. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25368. return;
  25369. }
  25370. _this._pointerCaptures[evt.pointerId] = true;
  25371. _this._startingPointerPosition.x = _this._pointerX;
  25372. _this._startingPointerPosition.y = _this._pointerY;
  25373. _this._startingPointerTime = Date.now();
  25374. if (!_this.pointerDownPredicate) {
  25375. _this.pointerDownPredicate = function (mesh) {
  25376. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25377. };
  25378. }
  25379. // Meshes
  25380. _this._pickedDownMesh = null;
  25381. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25382. _this._processPointerDown(pickResult, evt);
  25383. // Sprites
  25384. _this._pickedDownSprite = null;
  25385. if (_this.spriteManagers.length > 0) {
  25386. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25387. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25388. if (pickResult.pickedSprite.actionManager) {
  25389. _this._pickedDownSprite = pickResult.pickedSprite;
  25390. switch (evt.button) {
  25391. case 0:
  25392. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25393. break;
  25394. case 1:
  25395. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25396. break;
  25397. case 2:
  25398. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25399. break;
  25400. }
  25401. if (pickResult.pickedSprite.actionManager) {
  25402. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25403. }
  25404. }
  25405. }
  25406. }
  25407. };
  25408. this._onPointerUp = function (evt) {
  25409. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25410. return; // So we need to test it the pointer down was pressed before.
  25411. }
  25412. _this._totalPointersPressed--;
  25413. _this._pickedUpMesh = null;
  25414. _this._meshPickProceed = false;
  25415. _this._updatePointerPosition(evt);
  25416. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25417. // PreObservable support
  25418. if (_this.onPrePointerObservable.hasObservers()) {
  25419. if (!clickInfo.ignore) {
  25420. if (!clickInfo.hasSwiped) {
  25421. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25422. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25423. return;
  25424. }
  25425. }
  25426. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25427. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25428. return;
  25429. }
  25430. }
  25431. }
  25432. }
  25433. else {
  25434. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25435. return;
  25436. }
  25437. }
  25438. }
  25439. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25440. return;
  25441. }
  25442. _this._pointerCaptures[evt.pointerId] = false;
  25443. if (!_this.pointerUpPredicate) {
  25444. _this.pointerUpPredicate = function (mesh) {
  25445. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25446. };
  25447. }
  25448. // Meshes
  25449. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25450. _this._initActionManager(null, clickInfo);
  25451. }
  25452. if (!pickResult) {
  25453. pickResult = _this._currentPickResult;
  25454. }
  25455. _this._processPointerUp(pickResult, evt, clickInfo);
  25456. // Sprites
  25457. if (!clickInfo.ignore) {
  25458. if (_this.spriteManagers.length > 0) {
  25459. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25460. if (spritePickResult) {
  25461. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25462. if (spritePickResult.pickedSprite.actionManager) {
  25463. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25464. if (spritePickResult.pickedSprite.actionManager) {
  25465. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25466. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25467. }
  25468. }
  25469. }
  25470. }
  25471. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25472. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25473. }
  25474. }
  25475. }
  25476. }
  25477. _this._previousPickResult = _this._currentPickResult;
  25478. });
  25479. };
  25480. this._onKeyDown = function (evt) {
  25481. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25482. if (_this.onPreKeyboardObservable.hasObservers()) {
  25483. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25484. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25485. if (pi.skipOnPointerObservable) {
  25486. return;
  25487. }
  25488. }
  25489. if (_this.onKeyboardObservable.hasObservers()) {
  25490. var pi = new BABYLON.KeyboardInfo(type, evt);
  25491. _this.onKeyboardObservable.notifyObservers(pi, type);
  25492. }
  25493. if (_this.actionManager) {
  25494. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25495. }
  25496. };
  25497. this._onKeyUp = function (evt) {
  25498. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25499. if (_this.onPreKeyboardObservable.hasObservers()) {
  25500. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25501. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25502. if (pi.skipOnPointerObservable) {
  25503. return;
  25504. }
  25505. }
  25506. if (_this.onKeyboardObservable.hasObservers()) {
  25507. var pi = new BABYLON.KeyboardInfo(type, evt);
  25508. _this.onKeyboardObservable.notifyObservers(pi, type);
  25509. }
  25510. if (_this.actionManager) {
  25511. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25512. }
  25513. };
  25514. var engine = this.getEngine();
  25515. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25516. if (!canvas) {
  25517. return;
  25518. }
  25519. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25520. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25521. });
  25522. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25523. if (!canvas) {
  25524. return;
  25525. }
  25526. canvas.removeEventListener("keydown", _this._onKeyDown);
  25527. canvas.removeEventListener("keyup", _this._onKeyUp);
  25528. });
  25529. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25530. var canvas = this._engine.getRenderingCanvas();
  25531. if (!canvas) {
  25532. return;
  25533. }
  25534. if (attachMove) {
  25535. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25536. // Wheel
  25537. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25538. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25539. }
  25540. if (attachDown) {
  25541. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25542. }
  25543. if (attachUp) {
  25544. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25545. }
  25546. canvas.tabIndex = 1;
  25547. };
  25548. /** Detaches all event handlers*/
  25549. Scene.prototype.detachControl = function () {
  25550. var engine = this.getEngine();
  25551. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25552. var canvas = engine.getRenderingCanvas();
  25553. if (!canvas) {
  25554. return;
  25555. }
  25556. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25557. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25558. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25559. if (this._onCanvasBlurObserver) {
  25560. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25561. }
  25562. if (this._onCanvasFocusObserver) {
  25563. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25564. }
  25565. // Wheel
  25566. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25567. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25568. // Keyboard
  25569. canvas.removeEventListener("keydown", this._onKeyDown);
  25570. canvas.removeEventListener("keyup", this._onKeyUp);
  25571. // Observables
  25572. this.onKeyboardObservable.clear();
  25573. this.onPreKeyboardObservable.clear();
  25574. this.onPointerObservable.clear();
  25575. this.onPrePointerObservable.clear();
  25576. };
  25577. /**
  25578. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25579. * Delay loaded resources are not taking in account
  25580. * @return true if all required resources are ready
  25581. */
  25582. Scene.prototype.isReady = function () {
  25583. if (this._isDisposed) {
  25584. return false;
  25585. }
  25586. if (this._pendingData.length > 0) {
  25587. return false;
  25588. }
  25589. var index;
  25590. var engine = this.getEngine();
  25591. // Geometries
  25592. for (index = 0; index < this.geometries.length; index++) {
  25593. var geometry = this.geometries[index];
  25594. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25595. return false;
  25596. }
  25597. }
  25598. // Meshes
  25599. for (index = 0; index < this.meshes.length; index++) {
  25600. var mesh = this.meshes[index];
  25601. if (!mesh.isEnabled()) {
  25602. continue;
  25603. }
  25604. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25605. continue;
  25606. }
  25607. if (!mesh.isReady(true)) {
  25608. return false;
  25609. }
  25610. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25611. // Is Ready For Mesh
  25612. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25613. var step = _a[_i];
  25614. if (!step.action(mesh, hardwareInstancedRendering)) {
  25615. return false;
  25616. }
  25617. }
  25618. }
  25619. // Post-processes
  25620. if (this.activeCameras && this.activeCameras.length > 0) {
  25621. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25622. var camera = _c[_b];
  25623. if (!camera.isReady(true)) {
  25624. return false;
  25625. }
  25626. }
  25627. }
  25628. else if (this.activeCamera) {
  25629. if (!this.activeCamera.isReady(true)) {
  25630. return false;
  25631. }
  25632. }
  25633. // Particles
  25634. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25635. var particleSystem = _e[_d];
  25636. if (!particleSystem.isReady()) {
  25637. return false;
  25638. }
  25639. }
  25640. return true;
  25641. };
  25642. /** Resets all cached information relative to material (including effect and visibility) */
  25643. Scene.prototype.resetCachedMaterial = function () {
  25644. this._cachedMaterial = null;
  25645. this._cachedEffect = null;
  25646. this._cachedVisibility = null;
  25647. };
  25648. /**
  25649. * Registers a function to be called before every frame render
  25650. * @param func defines the function to register
  25651. */
  25652. Scene.prototype.registerBeforeRender = function (func) {
  25653. this.onBeforeRenderObservable.add(func);
  25654. };
  25655. /**
  25656. * Unregisters a function called before every frame render
  25657. * @param func defines the function to unregister
  25658. */
  25659. Scene.prototype.unregisterBeforeRender = function (func) {
  25660. this.onBeforeRenderObservable.removeCallback(func);
  25661. };
  25662. /**
  25663. * Registers a function to be called after every frame render
  25664. * @param func defines the function to register
  25665. */
  25666. Scene.prototype.registerAfterRender = function (func) {
  25667. this.onAfterRenderObservable.add(func);
  25668. };
  25669. /**
  25670. * Unregisters a function called after every frame render
  25671. * @param func defines the function to unregister
  25672. */
  25673. Scene.prototype.unregisterAfterRender = function (func) {
  25674. this.onAfterRenderObservable.removeCallback(func);
  25675. };
  25676. Scene.prototype._executeOnceBeforeRender = function (func) {
  25677. var _this = this;
  25678. var execFunc = function () {
  25679. func();
  25680. setTimeout(function () {
  25681. _this.unregisterBeforeRender(execFunc);
  25682. });
  25683. };
  25684. this.registerBeforeRender(execFunc);
  25685. };
  25686. /**
  25687. * The provided function will run before render once and will be disposed afterwards.
  25688. * A timeout delay can be provided so that the function will be executed in N ms.
  25689. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25690. * @param func The function to be executed.
  25691. * @param timeout optional delay in ms
  25692. */
  25693. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25694. var _this = this;
  25695. if (timeout !== undefined) {
  25696. setTimeout(function () {
  25697. _this._executeOnceBeforeRender(func);
  25698. }, timeout);
  25699. }
  25700. else {
  25701. this._executeOnceBeforeRender(func);
  25702. }
  25703. };
  25704. /** @hidden */
  25705. Scene.prototype._addPendingData = function (data) {
  25706. this._pendingData.push(data);
  25707. };
  25708. /** @hidden */
  25709. Scene.prototype._removePendingData = function (data) {
  25710. var wasLoading = this.isLoading;
  25711. var index = this._pendingData.indexOf(data);
  25712. if (index !== -1) {
  25713. this._pendingData.splice(index, 1);
  25714. }
  25715. if (wasLoading && !this.isLoading) {
  25716. this.onDataLoadedObservable.notifyObservers(this);
  25717. }
  25718. };
  25719. /**
  25720. * Returns the number of items waiting to be loaded
  25721. * @returns the number of items waiting to be loaded
  25722. */
  25723. Scene.prototype.getWaitingItemsCount = function () {
  25724. return this._pendingData.length;
  25725. };
  25726. Object.defineProperty(Scene.prototype, "isLoading", {
  25727. /**
  25728. * Returns a boolean indicating if the scene is still loading data
  25729. */
  25730. get: function () {
  25731. return this._pendingData.length > 0;
  25732. },
  25733. enumerable: true,
  25734. configurable: true
  25735. });
  25736. /**
  25737. * Registers a function to be executed when the scene is ready
  25738. * @param {Function} func - the function to be executed
  25739. */
  25740. Scene.prototype.executeWhenReady = function (func) {
  25741. var _this = this;
  25742. this.onReadyObservable.add(func);
  25743. if (this._executeWhenReadyTimeoutId !== -1) {
  25744. return;
  25745. }
  25746. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25747. _this._checkIsReady();
  25748. }, 150);
  25749. };
  25750. /**
  25751. * Returns a promise that resolves when the scene is ready
  25752. * @returns A promise that resolves when the scene is ready
  25753. */
  25754. Scene.prototype.whenReadyAsync = function () {
  25755. var _this = this;
  25756. return new Promise(function (resolve) {
  25757. _this.executeWhenReady(function () {
  25758. resolve();
  25759. });
  25760. });
  25761. };
  25762. /** @hidden */
  25763. Scene.prototype._checkIsReady = function () {
  25764. var _this = this;
  25765. this._registerTransientComponents();
  25766. if (this.isReady()) {
  25767. this.onReadyObservable.notifyObservers(this);
  25768. this.onReadyObservable.clear();
  25769. this._executeWhenReadyTimeoutId = -1;
  25770. return;
  25771. }
  25772. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25773. _this._checkIsReady();
  25774. }, 150);
  25775. };
  25776. // Animations
  25777. /**
  25778. * Will start the animation sequence of a given target
  25779. * @param target defines the target
  25780. * @param from defines from which frame should animation start
  25781. * @param to defines until which frame should animation run.
  25782. * @param weight defines the weight to apply to the animation (1.0 by default)
  25783. * @param loop defines if the animation loops
  25784. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25785. * @param onAnimationEnd defines the function to be executed when the animation ends
  25786. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25787. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25788. * @returns the animatable object created for this animation
  25789. */
  25790. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25791. if (weight === void 0) { weight = 1.0; }
  25792. if (speedRatio === void 0) { speedRatio = 1.0; }
  25793. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25794. returnedAnimatable.weight = weight;
  25795. return returnedAnimatable;
  25796. };
  25797. /**
  25798. * Will start the animation sequence of a given target
  25799. * @param target defines the target
  25800. * @param from defines from which frame should animation start
  25801. * @param to defines until which frame should animation run.
  25802. * @param loop defines if the animation loops
  25803. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25804. * @param onAnimationEnd defines the function to be executed when the animation ends
  25805. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25806. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25807. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25808. * @returns the animatable object created for this animation
  25809. */
  25810. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25811. if (speedRatio === void 0) { speedRatio = 1.0; }
  25812. if (stopCurrent === void 0) { stopCurrent = true; }
  25813. if (from > to && speedRatio > 0) {
  25814. speedRatio *= -1;
  25815. }
  25816. if (stopCurrent) {
  25817. this.stopAnimation(target, undefined, targetMask);
  25818. }
  25819. if (!animatable) {
  25820. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25821. }
  25822. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25823. // Local animations
  25824. if (target.animations && shouldRunTargetAnimations) {
  25825. animatable.appendAnimations(target, target.animations);
  25826. }
  25827. // Children animations
  25828. if (target.getAnimatables) {
  25829. var animatables = target.getAnimatables();
  25830. for (var index = 0; index < animatables.length; index++) {
  25831. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25832. }
  25833. }
  25834. animatable.reset();
  25835. return animatable;
  25836. };
  25837. /**
  25838. * Begin a new animation on a given node
  25839. * @param target defines the target where the animation will take place
  25840. * @param animations defines the list of animations to start
  25841. * @param from defines the initial value
  25842. * @param to defines the final value
  25843. * @param loop defines if you want animation to loop (off by default)
  25844. * @param speedRatio defines the speed ratio to apply to all animations
  25845. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25846. * @returns the list of created animatables
  25847. */
  25848. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25849. if (speedRatio === undefined) {
  25850. speedRatio = 1.0;
  25851. }
  25852. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25853. return animatable;
  25854. };
  25855. /**
  25856. * Begin a new animation on a given node and its hierarchy
  25857. * @param target defines the root node where the animation will take place
  25858. * @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.
  25859. * @param animations defines the list of animations to start
  25860. * @param from defines the initial value
  25861. * @param to defines the final value
  25862. * @param loop defines if you want animation to loop (off by default)
  25863. * @param speedRatio defines the speed ratio to apply to all animations
  25864. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25865. * @returns the list of animatables created for all nodes
  25866. */
  25867. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25868. var children = target.getDescendants(directDescendantsOnly);
  25869. var result = [];
  25870. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25871. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25872. var child = children_1[_i];
  25873. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25874. }
  25875. return result;
  25876. };
  25877. /**
  25878. * Gets the animatable associated with a specific target
  25879. * @param target defines the target of the animatable
  25880. * @returns the required animatable if found
  25881. */
  25882. Scene.prototype.getAnimatableByTarget = function (target) {
  25883. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25884. if (this._activeAnimatables[index].target === target) {
  25885. return this._activeAnimatables[index];
  25886. }
  25887. }
  25888. return null;
  25889. };
  25890. /**
  25891. * Gets all animatables associated with a given target
  25892. * @param target defines the target to look animatables for
  25893. * @returns an array of Animatables
  25894. */
  25895. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25896. var result = [];
  25897. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25898. if (this._activeAnimatables[index].target === target) {
  25899. result.push(this._activeAnimatables[index]);
  25900. }
  25901. }
  25902. return result;
  25903. };
  25904. Object.defineProperty(Scene.prototype, "animatables", {
  25905. /**
  25906. * Gets all animatable attached to the scene
  25907. */
  25908. get: function () {
  25909. return this._activeAnimatables;
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. /**
  25915. * Will stop the animation of the given target
  25916. * @param target - the target
  25917. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25918. * @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)
  25919. */
  25920. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25921. var animatables = this.getAllAnimatablesByTarget(target);
  25922. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25923. var animatable = animatables_1[_i];
  25924. animatable.stop(animationName, targetMask);
  25925. }
  25926. };
  25927. /**
  25928. * Stops and removes all animations that have been applied to the scene
  25929. */
  25930. Scene.prototype.stopAllAnimations = function () {
  25931. if (this._activeAnimatables) {
  25932. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25933. this._activeAnimatables[i].stop();
  25934. }
  25935. this._activeAnimatables = [];
  25936. }
  25937. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25938. var group = _a[_i];
  25939. group.stop();
  25940. }
  25941. };
  25942. Scene.prototype._animate = function () {
  25943. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25944. return;
  25945. }
  25946. // Getting time
  25947. var now = BABYLON.Tools.Now;
  25948. if (!this._animationTimeLast) {
  25949. if (this._pendingData.length > 0) {
  25950. return;
  25951. }
  25952. this._animationTimeLast = now;
  25953. }
  25954. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25955. this._animationTime += deltaTime;
  25956. this._animationTimeLast = now;
  25957. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25958. this._activeAnimatables[index]._animate(this._animationTime);
  25959. }
  25960. // Late animation bindings
  25961. this._processLateAnimationBindings();
  25962. };
  25963. /** @hidden */
  25964. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25965. var target = runtimeAnimation.target;
  25966. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25967. if (!target._lateAnimationHolders) {
  25968. target._lateAnimationHolders = {};
  25969. }
  25970. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25971. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25972. totalWeight: 0,
  25973. animations: [],
  25974. originalValue: originalValue
  25975. };
  25976. }
  25977. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25978. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25979. };
  25980. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25981. var normalizer = 1.0;
  25982. var finalPosition = BABYLON.Tmp.Vector3[0];
  25983. var finalScaling = BABYLON.Tmp.Vector3[1];
  25984. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25985. var startIndex = 0;
  25986. var originalAnimation = holder.animations[0];
  25987. var originalValue = holder.originalValue;
  25988. var scale = 1;
  25989. if (holder.totalWeight < 1.0) {
  25990. // We need to mix the original value in
  25991. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25992. scale = 1.0 - holder.totalWeight;
  25993. }
  25994. else {
  25995. startIndex = 1;
  25996. // We need to normalize the weights
  25997. normalizer = holder.totalWeight;
  25998. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25999. scale = originalAnimation.weight / normalizer;
  26000. if (scale == 1) {
  26001. return originalAnimation.currentValue;
  26002. }
  26003. }
  26004. finalScaling.scaleInPlace(scale);
  26005. finalPosition.scaleInPlace(scale);
  26006. finalQuaternion.scaleInPlace(scale);
  26007. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26008. var runtimeAnimation = holder.animations[animIndex];
  26009. var scale = runtimeAnimation.weight / normalizer;
  26010. var currentPosition = BABYLON.Tmp.Vector3[2];
  26011. var currentScaling = BABYLON.Tmp.Vector3[3];
  26012. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26013. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26014. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26015. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26016. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26017. }
  26018. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26019. return originalAnimation._workValue;
  26020. };
  26021. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26022. var originalAnimation = holder.animations[0];
  26023. var originalValue = holder.originalValue;
  26024. if (holder.animations.length === 1) {
  26025. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26026. }
  26027. var normalizer = 1.0;
  26028. var quaternions;
  26029. var weights;
  26030. if (holder.totalWeight < 1.0) {
  26031. var scale = 1.0 - holder.totalWeight;
  26032. quaternions = [];
  26033. weights = [];
  26034. quaternions.push(originalValue);
  26035. weights.push(scale);
  26036. }
  26037. else {
  26038. if (holder.animations.length === 2) { // Slerp as soon as we can
  26039. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26040. }
  26041. quaternions = [];
  26042. weights = [];
  26043. normalizer = holder.totalWeight;
  26044. }
  26045. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26046. var runtimeAnimation = holder.animations[animIndex];
  26047. quaternions.push(runtimeAnimation.currentValue);
  26048. weights.push(runtimeAnimation.weight / normalizer);
  26049. }
  26050. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26051. var cumulativeAmount = 0;
  26052. var cumulativeQuaternion = null;
  26053. for (var index = 0; index < quaternions.length;) {
  26054. if (!cumulativeQuaternion) {
  26055. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26056. cumulativeAmount = weights[index] + weights[index + 1];
  26057. index += 2;
  26058. continue;
  26059. }
  26060. cumulativeAmount += weights[index];
  26061. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26062. index++;
  26063. }
  26064. return cumulativeQuaternion;
  26065. };
  26066. Scene.prototype._processLateAnimationBindings = function () {
  26067. if (!this._registeredForLateAnimationBindings.length) {
  26068. return;
  26069. }
  26070. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26071. var target = this._registeredForLateAnimationBindings.data[index];
  26072. for (var path in target._lateAnimationHolders) {
  26073. var holder = target._lateAnimationHolders[path];
  26074. var originalAnimation = holder.animations[0];
  26075. var originalValue = holder.originalValue;
  26076. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26077. var finalValue = void 0;
  26078. if (matrixDecomposeMode) {
  26079. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26080. }
  26081. else {
  26082. var quaternionMode = originalValue.w !== undefined;
  26083. if (quaternionMode) {
  26084. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26085. }
  26086. else {
  26087. var startIndex = 0;
  26088. var normalizer = 1.0;
  26089. if (holder.totalWeight < 1.0) {
  26090. // We need to mix the original value in
  26091. if (originalValue.scale) {
  26092. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26093. }
  26094. else {
  26095. finalValue = originalValue * (1.0 - holder.totalWeight);
  26096. }
  26097. }
  26098. else {
  26099. // We need to normalize the weights
  26100. normalizer = holder.totalWeight;
  26101. var scale_1 = originalAnimation.weight / normalizer;
  26102. if (scale_1 !== 1) {
  26103. if (originalAnimation.currentValue.scale) {
  26104. finalValue = originalAnimation.currentValue.scale(scale_1);
  26105. }
  26106. else {
  26107. finalValue = originalAnimation.currentValue * scale_1;
  26108. }
  26109. }
  26110. else {
  26111. finalValue = originalAnimation.currentValue;
  26112. }
  26113. startIndex = 1;
  26114. }
  26115. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26116. var runtimeAnimation = holder.animations[animIndex];
  26117. var scale = runtimeAnimation.weight / normalizer;
  26118. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26119. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26120. }
  26121. else {
  26122. finalValue += runtimeAnimation.currentValue * scale;
  26123. }
  26124. }
  26125. }
  26126. }
  26127. target[path] = finalValue;
  26128. }
  26129. target._lateAnimationHolders = {};
  26130. }
  26131. this._registeredForLateAnimationBindings.reset();
  26132. };
  26133. // Matrix
  26134. /** @hidden */
  26135. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26136. this._useAlternateCameraConfiguration = active;
  26137. };
  26138. /**
  26139. * Gets the current view matrix
  26140. * @returns a Matrix
  26141. */
  26142. Scene.prototype.getViewMatrix = function () {
  26143. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26144. };
  26145. /**
  26146. * Gets the current projection matrix
  26147. * @returns a Matrix
  26148. */
  26149. Scene.prototype.getProjectionMatrix = function () {
  26150. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26151. };
  26152. /**
  26153. * Gets the current transform matrix
  26154. * @returns a Matrix made of View * Projection
  26155. */
  26156. Scene.prototype.getTransformMatrix = function () {
  26157. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26158. };
  26159. /**
  26160. * Sets the current transform matrix
  26161. * @param view defines the View matrix to use
  26162. * @param projection defines the Projection matrix to use
  26163. */
  26164. Scene.prototype.setTransformMatrix = function (view, projection) {
  26165. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26166. return;
  26167. }
  26168. this._viewUpdateFlag = view.updateFlag;
  26169. this._projectionUpdateFlag = projection.updateFlag;
  26170. this._viewMatrix = view;
  26171. this._projectionMatrix = projection;
  26172. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26173. // Update frustum
  26174. if (!this._frustumPlanes) {
  26175. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26176. }
  26177. else {
  26178. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26179. }
  26180. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26181. var otherCamera = this.activeCamera._alternateCamera;
  26182. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26183. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26184. }
  26185. if (this._sceneUbo.useUbo) {
  26186. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26187. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26188. this._sceneUbo.update();
  26189. }
  26190. };
  26191. /** @hidden */
  26192. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26193. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26194. return;
  26195. }
  26196. this._alternateViewUpdateFlag = view.updateFlag;
  26197. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26198. this._alternateViewMatrix = view;
  26199. this._alternateProjectionMatrix = projection;
  26200. if (!this._alternateTransformMatrix) {
  26201. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26202. }
  26203. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26204. if (!this._alternateSceneUbo) {
  26205. this._createAlternateUbo();
  26206. }
  26207. if (this._alternateSceneUbo.useUbo) {
  26208. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26209. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26210. this._alternateSceneUbo.update();
  26211. }
  26212. };
  26213. /**
  26214. * Gets the uniform buffer used to store scene data
  26215. * @returns a UniformBuffer
  26216. */
  26217. Scene.prototype.getSceneUniformBuffer = function () {
  26218. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26219. };
  26220. /**
  26221. * Gets an unique (relatively to the current scene) Id
  26222. * @returns an unique number for the scene
  26223. */
  26224. Scene.prototype.getUniqueId = function () {
  26225. var result = Scene._uniqueIdCounter;
  26226. Scene._uniqueIdCounter++;
  26227. return result;
  26228. };
  26229. /**
  26230. * Add a mesh to the list of scene's meshes
  26231. * @param newMesh defines the mesh to add
  26232. * @param recursive if all child meshes should also be added to the scene
  26233. */
  26234. Scene.prototype.addMesh = function (newMesh, recursive) {
  26235. var _this = this;
  26236. if (recursive === void 0) { recursive = false; }
  26237. this.meshes.push(newMesh);
  26238. //notify the collision coordinator
  26239. if (this.collisionCoordinator) {
  26240. this.collisionCoordinator.onMeshAdded(newMesh);
  26241. }
  26242. newMesh._resyncLightSources();
  26243. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26244. if (recursive) {
  26245. newMesh.getChildMeshes().forEach(function (m) {
  26246. _this.addMesh(m);
  26247. });
  26248. }
  26249. };
  26250. /**
  26251. * Remove a mesh for the list of scene's meshes
  26252. * @param toRemove defines the mesh to remove
  26253. * @param recursive if all child meshes should also be removed from the scene
  26254. * @returns the index where the mesh was in the mesh list
  26255. */
  26256. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26257. var _this = this;
  26258. if (recursive === void 0) { recursive = false; }
  26259. var index = this.meshes.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. // Remove from the scene if mesh found
  26262. this.meshes.splice(index, 1);
  26263. }
  26264. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26265. if (recursive) {
  26266. toRemove.getChildMeshes().forEach(function (m) {
  26267. _this.removeMesh(m);
  26268. });
  26269. }
  26270. return index;
  26271. };
  26272. /**
  26273. * Add a transform node to the list of scene's transform nodes
  26274. * @param newTransformNode defines the transform node to add
  26275. */
  26276. Scene.prototype.addTransformNode = function (newTransformNode) {
  26277. this.transformNodes.push(newTransformNode);
  26278. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26279. };
  26280. /**
  26281. * Remove a transform node for the list of scene's transform nodes
  26282. * @param toRemove defines the transform node to remove
  26283. * @returns the index where the transform node was in the transform node list
  26284. */
  26285. Scene.prototype.removeTransformNode = function (toRemove) {
  26286. var index = this.transformNodes.indexOf(toRemove);
  26287. if (index !== -1) {
  26288. // Remove from the scene if found
  26289. this.transformNodes.splice(index, 1);
  26290. }
  26291. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26292. return index;
  26293. };
  26294. /**
  26295. * Remove a skeleton for the list of scene's skeletons
  26296. * @param toRemove defines the skeleton to remove
  26297. * @returns the index where the skeleton was in the skeleton list
  26298. */
  26299. Scene.prototype.removeSkeleton = function (toRemove) {
  26300. var index = this.skeletons.indexOf(toRemove);
  26301. if (index !== -1) {
  26302. // Remove from the scene if found
  26303. this.skeletons.splice(index, 1);
  26304. }
  26305. return index;
  26306. };
  26307. /**
  26308. * Remove a morph target for the list of scene's morph targets
  26309. * @param toRemove defines the morph target to remove
  26310. * @returns the index where the morph target was in the morph target list
  26311. */
  26312. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26313. var index = this.morphTargetManagers.indexOf(toRemove);
  26314. if (index !== -1) {
  26315. // Remove from the scene if found
  26316. this.morphTargetManagers.splice(index, 1);
  26317. }
  26318. return index;
  26319. };
  26320. /**
  26321. * Remove a light for the list of scene's lights
  26322. * @param toRemove defines the light to remove
  26323. * @returns the index where the light was in the light list
  26324. */
  26325. Scene.prototype.removeLight = function (toRemove) {
  26326. var index = this.lights.indexOf(toRemove);
  26327. if (index !== -1) {
  26328. // Remove from meshes
  26329. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26330. var mesh = _a[_i];
  26331. mesh._removeLightSource(toRemove);
  26332. }
  26333. // Remove from the scene if mesh found
  26334. this.lights.splice(index, 1);
  26335. this.sortLightsByPriority();
  26336. }
  26337. this.onLightRemovedObservable.notifyObservers(toRemove);
  26338. return index;
  26339. };
  26340. /**
  26341. * Remove a camera for the list of scene's cameras
  26342. * @param toRemove defines the camera to remove
  26343. * @returns the index where the camera was in the camera list
  26344. */
  26345. Scene.prototype.removeCamera = function (toRemove) {
  26346. var index = this.cameras.indexOf(toRemove);
  26347. if (index !== -1) {
  26348. // Remove from the scene if mesh found
  26349. this.cameras.splice(index, 1);
  26350. }
  26351. // Remove from activeCameras
  26352. var index2 = this.activeCameras.indexOf(toRemove);
  26353. if (index2 !== -1) {
  26354. // Remove from the scene if mesh found
  26355. this.activeCameras.splice(index2, 1);
  26356. }
  26357. // Reset the activeCamera
  26358. if (this.activeCamera === toRemove) {
  26359. if (this.cameras.length > 0) {
  26360. this.activeCamera = this.cameras[0];
  26361. }
  26362. else {
  26363. this.activeCamera = null;
  26364. }
  26365. }
  26366. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26367. return index;
  26368. };
  26369. /**
  26370. * Remove a particle system for the list of scene's particle systems
  26371. * @param toRemove defines the particle system to remove
  26372. * @returns the index where the particle system was in the particle system list
  26373. */
  26374. Scene.prototype.removeParticleSystem = function (toRemove) {
  26375. var index = this.particleSystems.indexOf(toRemove);
  26376. if (index !== -1) {
  26377. this.particleSystems.splice(index, 1);
  26378. }
  26379. return index;
  26380. };
  26381. /**
  26382. * Remove a animation for the list of scene's animations
  26383. * @param toRemove defines the animation to remove
  26384. * @returns the index where the animation was in the animation list
  26385. */
  26386. Scene.prototype.removeAnimation = function (toRemove) {
  26387. var index = this.animations.indexOf(toRemove);
  26388. if (index !== -1) {
  26389. this.animations.splice(index, 1);
  26390. }
  26391. return index;
  26392. };
  26393. /**
  26394. * Removes the given animation group from this scene.
  26395. * @param toRemove The animation group to remove
  26396. * @returns The index of the removed animation group
  26397. */
  26398. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26399. var index = this.animationGroups.indexOf(toRemove);
  26400. if (index !== -1) {
  26401. this.animationGroups.splice(index, 1);
  26402. }
  26403. return index;
  26404. };
  26405. /**
  26406. * Removes the given multi-material from this scene.
  26407. * @param toRemove The multi-material to remove
  26408. * @returns The index of the removed multi-material
  26409. */
  26410. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26411. var index = this.multiMaterials.indexOf(toRemove);
  26412. if (index !== -1) {
  26413. this.multiMaterials.splice(index, 1);
  26414. }
  26415. return index;
  26416. };
  26417. /**
  26418. * Removes the given material from this scene.
  26419. * @param toRemove The material to remove
  26420. * @returns The index of the removed material
  26421. */
  26422. Scene.prototype.removeMaterial = function (toRemove) {
  26423. var index = this.materials.indexOf(toRemove);
  26424. if (index !== -1) {
  26425. this.materials.splice(index, 1);
  26426. }
  26427. return index;
  26428. };
  26429. /**
  26430. * Removes the given action manager from this scene.
  26431. * @param toRemove The action manager to remove
  26432. * @returns The index of the removed action manager
  26433. */
  26434. Scene.prototype.removeActionManager = function (toRemove) {
  26435. var index = this.actionManagers.indexOf(toRemove);
  26436. if (index !== -1) {
  26437. this.actionManagers.splice(index, 1);
  26438. }
  26439. return index;
  26440. };
  26441. /**
  26442. * Removes the given texture from this scene.
  26443. * @param toRemove The texture to remove
  26444. * @returns The index of the removed texture
  26445. */
  26446. Scene.prototype.removeTexture = function (toRemove) {
  26447. var index = this.textures.indexOf(toRemove);
  26448. if (index !== -1) {
  26449. this.textures.splice(index, 1);
  26450. }
  26451. return index;
  26452. };
  26453. /**
  26454. * Adds the given light to this scene
  26455. * @param newLight The light to add
  26456. */
  26457. Scene.prototype.addLight = function (newLight) {
  26458. this.lights.push(newLight);
  26459. this.sortLightsByPriority();
  26460. // Add light to all meshes (To support if the light is removed and then readded)
  26461. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26462. var mesh = _a[_i];
  26463. if (mesh._lightSources.indexOf(newLight) === -1) {
  26464. mesh._lightSources.push(newLight);
  26465. mesh._resyncLightSources();
  26466. }
  26467. }
  26468. this.onNewLightAddedObservable.notifyObservers(newLight);
  26469. };
  26470. /**
  26471. * Sorts the list list based on light priorities
  26472. */
  26473. Scene.prototype.sortLightsByPriority = function () {
  26474. if (this.requireLightSorting) {
  26475. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26476. }
  26477. };
  26478. /**
  26479. * Adds the given camera to this scene
  26480. * @param newCamera The camera to add
  26481. */
  26482. Scene.prototype.addCamera = function (newCamera) {
  26483. this.cameras.push(newCamera);
  26484. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26485. };
  26486. /**
  26487. * Adds the given skeleton to this scene
  26488. * @param newSkeleton The skeleton to add
  26489. */
  26490. Scene.prototype.addSkeleton = function (newSkeleton) {
  26491. this.skeletons.push(newSkeleton);
  26492. };
  26493. /**
  26494. * Adds the given particle system to this scene
  26495. * @param newParticleSystem The particle system to add
  26496. */
  26497. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26498. this.particleSystems.push(newParticleSystem);
  26499. };
  26500. /**
  26501. * Adds the given animation to this scene
  26502. * @param newAnimation The animation to add
  26503. */
  26504. Scene.prototype.addAnimation = function (newAnimation) {
  26505. this.animations.push(newAnimation);
  26506. };
  26507. /**
  26508. * Adds the given animation group to this scene.
  26509. * @param newAnimationGroup The animation group to add
  26510. */
  26511. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26512. this.animationGroups.push(newAnimationGroup);
  26513. };
  26514. /**
  26515. * Adds the given multi-material to this scene
  26516. * @param newMultiMaterial The multi-material to add
  26517. */
  26518. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26519. this.multiMaterials.push(newMultiMaterial);
  26520. };
  26521. /**
  26522. * Adds the given material to this scene
  26523. * @param newMaterial The material to add
  26524. */
  26525. Scene.prototype.addMaterial = function (newMaterial) {
  26526. this.materials.push(newMaterial);
  26527. };
  26528. /**
  26529. * Adds the given morph target to this scene
  26530. * @param newMorphTargetManager The morph target to add
  26531. */
  26532. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26533. this.morphTargetManagers.push(newMorphTargetManager);
  26534. };
  26535. /**
  26536. * Adds the given geometry to this scene
  26537. * @param newGeometry The geometry to add
  26538. */
  26539. Scene.prototype.addGeometry = function (newGeometry) {
  26540. this.geometries.push(newGeometry);
  26541. };
  26542. /**
  26543. * Adds the given action manager to this scene
  26544. * @param newActionManager The action manager to add
  26545. */
  26546. Scene.prototype.addActionManager = function (newActionManager) {
  26547. this.actionManagers.push(newActionManager);
  26548. };
  26549. /**
  26550. * Adds the given texture to this scene.
  26551. * @param newTexture The texture to add
  26552. */
  26553. Scene.prototype.addTexture = function (newTexture) {
  26554. this.textures.push(newTexture);
  26555. };
  26556. /**
  26557. * Switch active camera
  26558. * @param newCamera defines the new active camera
  26559. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26560. */
  26561. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26562. if (attachControl === void 0) { attachControl = true; }
  26563. var canvas = this._engine.getRenderingCanvas();
  26564. if (!canvas) {
  26565. return;
  26566. }
  26567. if (this.activeCamera) {
  26568. this.activeCamera.detachControl(canvas);
  26569. }
  26570. this.activeCamera = newCamera;
  26571. if (attachControl) {
  26572. newCamera.attachControl(canvas);
  26573. }
  26574. };
  26575. /**
  26576. * sets the active camera of the scene using its ID
  26577. * @param id defines the camera's ID
  26578. * @return the new active camera or null if none found.
  26579. */
  26580. Scene.prototype.setActiveCameraByID = function (id) {
  26581. var camera = this.getCameraByID(id);
  26582. if (camera) {
  26583. this.activeCamera = camera;
  26584. return camera;
  26585. }
  26586. return null;
  26587. };
  26588. /**
  26589. * sets the active camera of the scene using its name
  26590. * @param name defines the camera's name
  26591. * @returns the new active camera or null if none found.
  26592. */
  26593. Scene.prototype.setActiveCameraByName = function (name) {
  26594. var camera = this.getCameraByName(name);
  26595. if (camera) {
  26596. this.activeCamera = camera;
  26597. return camera;
  26598. }
  26599. return null;
  26600. };
  26601. /**
  26602. * get an animation group using its name
  26603. * @param name defines the material's name
  26604. * @return the animation group or null if none found.
  26605. */
  26606. Scene.prototype.getAnimationGroupByName = function (name) {
  26607. for (var index = 0; index < this.animationGroups.length; index++) {
  26608. if (this.animationGroups[index].name === name) {
  26609. return this.animationGroups[index];
  26610. }
  26611. }
  26612. return null;
  26613. };
  26614. /**
  26615. * get a material using its id
  26616. * @param id defines the material's ID
  26617. * @return the material or null if none found.
  26618. */
  26619. Scene.prototype.getMaterialByID = function (id) {
  26620. for (var index = 0; index < this.materials.length; index++) {
  26621. if (this.materials[index].id === id) {
  26622. return this.materials[index];
  26623. }
  26624. }
  26625. return null;
  26626. };
  26627. /**
  26628. * Gets a material using its name
  26629. * @param name defines the material's name
  26630. * @return the material or null if none found.
  26631. */
  26632. Scene.prototype.getMaterialByName = function (name) {
  26633. for (var index = 0; index < this.materials.length; index++) {
  26634. if (this.materials[index].name === name) {
  26635. return this.materials[index];
  26636. }
  26637. }
  26638. return null;
  26639. };
  26640. /**
  26641. * Gets a camera using its id
  26642. * @param id defines the id to look for
  26643. * @returns the camera or null if not found
  26644. */
  26645. Scene.prototype.getCameraByID = function (id) {
  26646. for (var index = 0; index < this.cameras.length; index++) {
  26647. if (this.cameras[index].id === id) {
  26648. return this.cameras[index];
  26649. }
  26650. }
  26651. return null;
  26652. };
  26653. /**
  26654. * Gets a camera using its unique id
  26655. * @param uniqueId defines the unique id to look for
  26656. * @returns the camera or null if not found
  26657. */
  26658. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26659. for (var index = 0; index < this.cameras.length; index++) {
  26660. if (this.cameras[index].uniqueId === uniqueId) {
  26661. return this.cameras[index];
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. /**
  26667. * Gets a camera using its name
  26668. * @param name defines the camera's name
  26669. * @return the camera or null if none found.
  26670. */
  26671. Scene.prototype.getCameraByName = function (name) {
  26672. for (var index = 0; index < this.cameras.length; index++) {
  26673. if (this.cameras[index].name === name) {
  26674. return this.cameras[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Gets a bone using its id
  26681. * @param id defines the bone's id
  26682. * @return the bone or null if not found
  26683. */
  26684. Scene.prototype.getBoneByID = function (id) {
  26685. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26686. var skeleton = this.skeletons[skeletonIndex];
  26687. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26688. if (skeleton.bones[boneIndex].id === id) {
  26689. return skeleton.bones[boneIndex];
  26690. }
  26691. }
  26692. }
  26693. return null;
  26694. };
  26695. /**
  26696. * Gets a bone using its id
  26697. * @param name defines the bone's name
  26698. * @return the bone or null if not found
  26699. */
  26700. Scene.prototype.getBoneByName = function (name) {
  26701. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26702. var skeleton = this.skeletons[skeletonIndex];
  26703. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26704. if (skeleton.bones[boneIndex].name === name) {
  26705. return skeleton.bones[boneIndex];
  26706. }
  26707. }
  26708. }
  26709. return null;
  26710. };
  26711. /**
  26712. * Gets a light node using its name
  26713. * @param name defines the the light's name
  26714. * @return the light or null if none found.
  26715. */
  26716. Scene.prototype.getLightByName = function (name) {
  26717. for (var index = 0; index < this.lights.length; index++) {
  26718. if (this.lights[index].name === name) {
  26719. return this.lights[index];
  26720. }
  26721. }
  26722. return null;
  26723. };
  26724. /**
  26725. * Gets a light node using its id
  26726. * @param id defines the light's id
  26727. * @return the light or null if none found.
  26728. */
  26729. Scene.prototype.getLightByID = function (id) {
  26730. for (var index = 0; index < this.lights.length; index++) {
  26731. if (this.lights[index].id === id) {
  26732. return this.lights[index];
  26733. }
  26734. }
  26735. return null;
  26736. };
  26737. /**
  26738. * Gets a light node using its scene-generated unique ID
  26739. * @param uniqueId defines the light's unique id
  26740. * @return the light or null if none found.
  26741. */
  26742. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26743. for (var index = 0; index < this.lights.length; index++) {
  26744. if (this.lights[index].uniqueId === uniqueId) {
  26745. return this.lights[index];
  26746. }
  26747. }
  26748. return null;
  26749. };
  26750. /**
  26751. * Gets a particle system by id
  26752. * @param id defines the particle system id
  26753. * @return the corresponding system or null if none found
  26754. */
  26755. Scene.prototype.getParticleSystemByID = function (id) {
  26756. for (var index = 0; index < this.particleSystems.length; index++) {
  26757. if (this.particleSystems[index].id === id) {
  26758. return this.particleSystems[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a geometry using its ID
  26765. * @param id defines the geometry's id
  26766. * @return the geometry or null if none found.
  26767. */
  26768. Scene.prototype.getGeometryByID = function (id) {
  26769. for (var index = 0; index < this.geometries.length; index++) {
  26770. if (this.geometries[index].id === id) {
  26771. return this.geometries[index];
  26772. }
  26773. }
  26774. return null;
  26775. };
  26776. /**
  26777. * Add a new geometry to this scene
  26778. * @param geometry defines the geometry to be added to the scene.
  26779. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26780. * @return a boolean defining if the geometry was added or not
  26781. */
  26782. Scene.prototype.pushGeometry = function (geometry, force) {
  26783. if (!force && this.getGeometryByID(geometry.id)) {
  26784. return false;
  26785. }
  26786. this.geometries.push(geometry);
  26787. //notify the collision coordinator
  26788. if (this.collisionCoordinator) {
  26789. this.collisionCoordinator.onGeometryAdded(geometry);
  26790. }
  26791. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26792. return true;
  26793. };
  26794. /**
  26795. * Removes an existing geometry
  26796. * @param geometry defines the geometry to be removed from the scene
  26797. * @return a boolean defining if the geometry was removed or not
  26798. */
  26799. Scene.prototype.removeGeometry = function (geometry) {
  26800. var index = this.geometries.indexOf(geometry);
  26801. if (index > -1) {
  26802. this.geometries.splice(index, 1);
  26803. //notify the collision coordinator
  26804. if (this.collisionCoordinator) {
  26805. this.collisionCoordinator.onGeometryDeleted(geometry);
  26806. }
  26807. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26808. return true;
  26809. }
  26810. return false;
  26811. };
  26812. /**
  26813. * Gets the list of geometries attached to the scene
  26814. * @returns an array of Geometry
  26815. */
  26816. Scene.prototype.getGeometries = function () {
  26817. return this.geometries;
  26818. };
  26819. /**
  26820. * Gets the first added mesh found of a given ID
  26821. * @param id defines the id to search for
  26822. * @return the mesh found or null if not found at all
  26823. */
  26824. Scene.prototype.getMeshByID = function (id) {
  26825. for (var index = 0; index < this.meshes.length; index++) {
  26826. if (this.meshes[index].id === id) {
  26827. return this.meshes[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a list of meshes using their id
  26834. * @param id defines the id to search for
  26835. * @returns a list of meshes
  26836. */
  26837. Scene.prototype.getMeshesByID = function (id) {
  26838. return this.meshes.filter(function (m) {
  26839. return m.id === id;
  26840. });
  26841. };
  26842. /**
  26843. * Gets the first added transform node found of a given ID
  26844. * @param id defines the id to search for
  26845. * @return the found transform node or null if not found at all.
  26846. */
  26847. Scene.prototype.getTransformNodeByID = function (id) {
  26848. for (var index = 0; index < this.transformNodes.length; index++) {
  26849. if (this.transformNodes[index].id === id) {
  26850. return this.transformNodes[index];
  26851. }
  26852. }
  26853. return null;
  26854. };
  26855. /**
  26856. * Gets a list of transform nodes using their id
  26857. * @param id defines the id to search for
  26858. * @returns a list of transform nodes
  26859. */
  26860. Scene.prototype.getTransformNodesByID = function (id) {
  26861. return this.transformNodes.filter(function (m) {
  26862. return m.id === id;
  26863. });
  26864. };
  26865. /**
  26866. * Gets a mesh with its auto-generated unique id
  26867. * @param uniqueId defines the unique id to search for
  26868. * @return the found mesh or null if not found at all.
  26869. */
  26870. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26871. for (var index = 0; index < this.meshes.length; index++) {
  26872. if (this.meshes[index].uniqueId === uniqueId) {
  26873. return this.meshes[index];
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. /**
  26879. * Gets a the last added mesh using a given id
  26880. * @param id defines the id to search for
  26881. * @return the found mesh or null if not found at all.
  26882. */
  26883. Scene.prototype.getLastMeshByID = function (id) {
  26884. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26885. if (this.meshes[index].id === id) {
  26886. return this.meshes[index];
  26887. }
  26888. }
  26889. return null;
  26890. };
  26891. /**
  26892. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26893. * @param id defines the id to search for
  26894. * @return the found node or null if not found at all
  26895. */
  26896. Scene.prototype.getLastEntryByID = function (id) {
  26897. var index;
  26898. for (index = this.meshes.length - 1; index >= 0; index--) {
  26899. if (this.meshes[index].id === id) {
  26900. return this.meshes[index];
  26901. }
  26902. }
  26903. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26904. if (this.transformNodes[index].id === id) {
  26905. return this.transformNodes[index];
  26906. }
  26907. }
  26908. for (index = this.cameras.length - 1; index >= 0; index--) {
  26909. if (this.cameras[index].id === id) {
  26910. return this.cameras[index];
  26911. }
  26912. }
  26913. for (index = this.lights.length - 1; index >= 0; index--) {
  26914. if (this.lights[index].id === id) {
  26915. return this.lights[index];
  26916. }
  26917. }
  26918. return null;
  26919. };
  26920. /**
  26921. * Gets a node (Mesh, Camera, Light) using a given id
  26922. * @param id defines the id to search for
  26923. * @return the found node or null if not found at all
  26924. */
  26925. Scene.prototype.getNodeByID = function (id) {
  26926. var mesh = this.getMeshByID(id);
  26927. if (mesh) {
  26928. return mesh;
  26929. }
  26930. var light = this.getLightByID(id);
  26931. if (light) {
  26932. return light;
  26933. }
  26934. var camera = this.getCameraByID(id);
  26935. if (camera) {
  26936. return camera;
  26937. }
  26938. var bone = this.getBoneByID(id);
  26939. return bone;
  26940. };
  26941. /**
  26942. * Gets a node (Mesh, Camera, Light) using a given name
  26943. * @param name defines the name to search for
  26944. * @return the found node or null if not found at all.
  26945. */
  26946. Scene.prototype.getNodeByName = function (name) {
  26947. var mesh = this.getMeshByName(name);
  26948. if (mesh) {
  26949. return mesh;
  26950. }
  26951. var light = this.getLightByName(name);
  26952. if (light) {
  26953. return light;
  26954. }
  26955. var camera = this.getCameraByName(name);
  26956. if (camera) {
  26957. return camera;
  26958. }
  26959. var bone = this.getBoneByName(name);
  26960. return bone;
  26961. };
  26962. /**
  26963. * Gets a mesh using a given name
  26964. * @param name defines the name to search for
  26965. * @return the found mesh or null if not found at all.
  26966. */
  26967. Scene.prototype.getMeshByName = function (name) {
  26968. for (var index = 0; index < this.meshes.length; index++) {
  26969. if (this.meshes[index].name === name) {
  26970. return this.meshes[index];
  26971. }
  26972. }
  26973. return null;
  26974. };
  26975. /**
  26976. * Gets a transform node using a given name
  26977. * @param name defines the name to search for
  26978. * @return the found transform node or null if not found at all.
  26979. */
  26980. Scene.prototype.getTransformNodeByName = function (name) {
  26981. for (var index = 0; index < this.transformNodes.length; index++) {
  26982. if (this.transformNodes[index].name === name) {
  26983. return this.transformNodes[index];
  26984. }
  26985. }
  26986. return null;
  26987. };
  26988. /**
  26989. * Gets a sound using a given name
  26990. * @param name defines the name to search for
  26991. * @return the found sound or null if not found at all.
  26992. */
  26993. Scene.prototype.getSoundByName = function (name) {
  26994. var index;
  26995. if (BABYLON.AudioEngine) {
  26996. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26997. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26998. return this.mainSoundTrack.soundCollection[index];
  26999. }
  27000. }
  27001. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27002. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27003. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27004. return this.soundTracks[sdIndex].soundCollection[index];
  27005. }
  27006. }
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27013. * @param id defines the id to search for
  27014. * @return the found skeleton or null if not found at all.
  27015. */
  27016. Scene.prototype.getLastSkeletonByID = function (id) {
  27017. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27018. if (this.skeletons[index].id === id) {
  27019. return this.skeletons[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27026. * @param id defines the id to search for
  27027. * @return the found skeleton or null if not found at all.
  27028. */
  27029. Scene.prototype.getSkeletonById = function (id) {
  27030. for (var index = 0; index < this.skeletons.length; index++) {
  27031. if (this.skeletons[index].id === id) {
  27032. return this.skeletons[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a skeleton using a given name
  27039. * @param name defines the name to search for
  27040. * @return the found skeleton or null if not found at all.
  27041. */
  27042. Scene.prototype.getSkeletonByName = function (name) {
  27043. for (var index = 0; index < this.skeletons.length; index++) {
  27044. if (this.skeletons[index].name === name) {
  27045. return this.skeletons[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27052. * @param id defines the id to search for
  27053. * @return the found morph target manager or null if not found at all.
  27054. */
  27055. Scene.prototype.getMorphTargetManagerById = function (id) {
  27056. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27057. if (this.morphTargetManagers[index].uniqueId === id) {
  27058. return this.morphTargetManagers[index];
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Gets a boolean indicating if the given mesh is active
  27065. * @param mesh defines the mesh to look for
  27066. * @returns true if the mesh is in the active list
  27067. */
  27068. Scene.prototype.isActiveMesh = function (mesh) {
  27069. return (this._activeMeshes.indexOf(mesh) !== -1);
  27070. };
  27071. Object.defineProperty(Scene.prototype, "uid", {
  27072. /**
  27073. * Return a unique id as a string which can serve as an identifier for the scene
  27074. */
  27075. get: function () {
  27076. if (!this._uid) {
  27077. this._uid = BABYLON.Tools.RandomId();
  27078. }
  27079. return this._uid;
  27080. },
  27081. enumerable: true,
  27082. configurable: true
  27083. });
  27084. /**
  27085. * Add an externaly attached data from its key.
  27086. * This method call will fail and return false, if such key already exists.
  27087. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27088. * @param key the unique key that identifies the data
  27089. * @param data the data object to associate to the key for this Engine instance
  27090. * @return true if no such key were already present and the data was added successfully, false otherwise
  27091. */
  27092. Scene.prototype.addExternalData = function (key, data) {
  27093. if (!this._externalData) {
  27094. this._externalData = new BABYLON.StringDictionary();
  27095. }
  27096. return this._externalData.add(key, data);
  27097. };
  27098. /**
  27099. * Get an externaly attached data from its key
  27100. * @param key the unique key that identifies the data
  27101. * @return the associated data, if present (can be null), or undefined if not present
  27102. */
  27103. Scene.prototype.getExternalData = function (key) {
  27104. if (!this._externalData) {
  27105. return null;
  27106. }
  27107. return this._externalData.get(key);
  27108. };
  27109. /**
  27110. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27111. * @param key the unique key that identifies the data
  27112. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27113. * @return the associated data, can be null if the factory returned null.
  27114. */
  27115. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27116. if (!this._externalData) {
  27117. this._externalData = new BABYLON.StringDictionary();
  27118. }
  27119. return this._externalData.getOrAddWithFactory(key, factory);
  27120. };
  27121. /**
  27122. * Remove an externaly attached data from the Engine instance
  27123. * @param key the unique key that identifies the data
  27124. * @return true if the data was successfully removed, false if it doesn't exist
  27125. */
  27126. Scene.prototype.removeExternalData = function (key) {
  27127. return this._externalData.remove(key);
  27128. };
  27129. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27130. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27131. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27132. var step = _a[_i];
  27133. step.action(mesh, subMesh);
  27134. }
  27135. var material = subMesh.getMaterial();
  27136. if (material !== null && material !== undefined) {
  27137. // Render targets
  27138. if (material.getRenderTargetTextures !== undefined) {
  27139. if (this._processedMaterials.indexOf(material) === -1) {
  27140. this._processedMaterials.push(material);
  27141. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27142. }
  27143. }
  27144. // Dispatch
  27145. this._activeIndices.addCount(subMesh.indexCount, false);
  27146. this._renderingManager.dispatch(subMesh, mesh, material);
  27147. }
  27148. }
  27149. };
  27150. /**
  27151. * Clear the processed materials smart array preventing retention point in material dispose.
  27152. */
  27153. Scene.prototype.freeProcessedMaterials = function () {
  27154. this._processedMaterials.dispose();
  27155. };
  27156. /**
  27157. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27158. */
  27159. Scene.prototype.freeActiveMeshes = function () {
  27160. this._activeMeshes.dispose();
  27161. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27162. this.activeCamera._activeMeshes.dispose();
  27163. }
  27164. if (this.activeCameras) {
  27165. for (var i = 0; i < this.activeCameras.length; i++) {
  27166. var activeCamera = this.activeCameras[i];
  27167. if (activeCamera && activeCamera._activeMeshes) {
  27168. activeCamera._activeMeshes.dispose();
  27169. }
  27170. }
  27171. }
  27172. };
  27173. /**
  27174. * Clear the info related to rendering groups preventing retention points during dispose.
  27175. */
  27176. Scene.prototype.freeRenderingGroups = function () {
  27177. if (this._renderingManager) {
  27178. this._renderingManager.freeRenderingGroups();
  27179. }
  27180. if (this.textures) {
  27181. for (var i = 0; i < this.textures.length; i++) {
  27182. var texture = this.textures[i];
  27183. if (texture && texture.renderList) {
  27184. texture.freeRenderingGroups();
  27185. }
  27186. }
  27187. }
  27188. };
  27189. /** @hidden */
  27190. Scene.prototype._isInIntermediateRendering = function () {
  27191. return this._intermediateRendering;
  27192. };
  27193. /**
  27194. * Defines the current active mesh candidate provider
  27195. * @param provider defines the provider to use
  27196. */
  27197. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27198. this._activeMeshCandidateProvider = provider;
  27199. };
  27200. /**
  27201. * Gets the current active mesh candidate provider
  27202. * @returns the current active mesh candidate provider
  27203. */
  27204. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27205. return this._activeMeshCandidateProvider;
  27206. };
  27207. /**
  27208. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27209. * @returns the current scene
  27210. */
  27211. Scene.prototype.freezeActiveMeshes = function () {
  27212. if (!this.activeCamera) {
  27213. return this;
  27214. }
  27215. if (!this._frustumPlanes) {
  27216. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27217. }
  27218. this._evaluateActiveMeshes();
  27219. this._activeMeshesFrozen = true;
  27220. return this;
  27221. };
  27222. /**
  27223. * Use this function to restart evaluating active meshes on every frame
  27224. * @returns the current scene
  27225. */
  27226. Scene.prototype.unfreezeActiveMeshes = function () {
  27227. this._activeMeshesFrozen = false;
  27228. return this;
  27229. };
  27230. Scene.prototype._evaluateActiveMeshes = function () {
  27231. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27232. return;
  27233. }
  27234. if (!this.activeCamera) {
  27235. return;
  27236. }
  27237. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27238. this.activeCamera._activeMeshes.reset();
  27239. this._activeMeshes.reset();
  27240. this._renderingManager.reset();
  27241. this._processedMaterials.reset();
  27242. this._activeParticleSystems.reset();
  27243. this._activeSkeletons.reset();
  27244. this._softwareSkinnedMeshes.reset();
  27245. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27246. var step = _a[_i];
  27247. step.action();
  27248. }
  27249. // Meshes
  27250. var meshes;
  27251. var len;
  27252. var checkIsEnabled = true;
  27253. // Determine mesh candidates
  27254. if (this._activeMeshCandidateProvider !== undefined) {
  27255. // Use _activeMeshCandidateProvider
  27256. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27257. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27258. if (meshes !== undefined) {
  27259. len = meshes.length;
  27260. }
  27261. else {
  27262. len = 0;
  27263. }
  27264. }
  27265. else if (this._selectionOctree !== undefined) {
  27266. // Octree
  27267. var selection = this._selectionOctree.select(this._frustumPlanes);
  27268. meshes = selection.data;
  27269. len = selection.length;
  27270. }
  27271. else {
  27272. // Full scene traversal
  27273. len = this.meshes.length;
  27274. meshes = this.meshes;
  27275. }
  27276. // Check each mesh
  27277. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27278. mesh = meshes[meshIndex];
  27279. if (mesh.isBlocked) {
  27280. continue;
  27281. }
  27282. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27283. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27284. continue;
  27285. }
  27286. mesh.computeWorldMatrix();
  27287. // Intersections
  27288. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27289. this._meshesForIntersections.pushNoDuplicate(mesh);
  27290. }
  27291. // Switch to current LOD
  27292. meshLOD = mesh.getLOD(this.activeCamera);
  27293. if (meshLOD === undefined || meshLOD === null) {
  27294. continue;
  27295. }
  27296. mesh._preActivate();
  27297. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27298. this._activeMeshes.push(mesh);
  27299. this.activeCamera._activeMeshes.push(mesh);
  27300. mesh._activate(this._renderId);
  27301. if (meshLOD !== mesh) {
  27302. meshLOD._activate(this._renderId);
  27303. }
  27304. this._activeMesh(mesh, meshLOD);
  27305. }
  27306. }
  27307. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27308. // Particle systems
  27309. if (this.particlesEnabled) {
  27310. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27311. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27312. var particleSystem = this.particleSystems[particleIndex];
  27313. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27314. continue;
  27315. }
  27316. var emitter = particleSystem.emitter;
  27317. if (!emitter.position || emitter.isEnabled()) {
  27318. this._activeParticleSystems.push(particleSystem);
  27319. particleSystem.animate();
  27320. this._renderingManager.dispatchParticles(particleSystem);
  27321. }
  27322. }
  27323. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27324. }
  27325. };
  27326. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27327. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27328. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27329. mesh.skeleton.prepare();
  27330. }
  27331. if (!mesh.computeBonesUsingShaders) {
  27332. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27333. }
  27334. }
  27335. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27336. var step = _a[_i];
  27337. step.action(sourceMesh, mesh);
  27338. }
  27339. if (mesh !== undefined && mesh !== null
  27340. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27341. // Submeshes Octrees
  27342. var len;
  27343. var subMeshes;
  27344. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27345. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27346. len = intersections.length;
  27347. subMeshes = intersections.data;
  27348. }
  27349. else {
  27350. subMeshes = mesh.subMeshes;
  27351. len = subMeshes.length;
  27352. }
  27353. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27354. subMesh = subMeshes[subIndex];
  27355. this._evaluateSubMesh(subMesh, mesh);
  27356. }
  27357. }
  27358. };
  27359. /**
  27360. * Update the transform matrix to update from the current active camera
  27361. * @param force defines a boolean used to force the update even if cache is up to date
  27362. */
  27363. Scene.prototype.updateTransformMatrix = function (force) {
  27364. if (!this.activeCamera) {
  27365. return;
  27366. }
  27367. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27368. };
  27369. /**
  27370. * 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)
  27371. * @param alternateCamera defines the camera to use
  27372. */
  27373. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27374. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27375. };
  27376. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27377. if (camera && camera._skipRendering) {
  27378. return;
  27379. }
  27380. var engine = this._engine;
  27381. this.activeCamera = camera;
  27382. if (!this.activeCamera)
  27383. throw new Error("Active camera not set");
  27384. // Viewport
  27385. engine.setViewport(this.activeCamera.viewport);
  27386. // Camera
  27387. this.resetCachedMaterial();
  27388. this._renderId++;
  27389. this.updateTransformMatrix();
  27390. if (camera._alternateCamera) {
  27391. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27392. this._alternateRendering = true;
  27393. }
  27394. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27395. // Meshes
  27396. this._evaluateActiveMeshes();
  27397. // Software skinning
  27398. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27399. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27400. mesh.applySkeleton(mesh.skeleton);
  27401. }
  27402. // Render targets
  27403. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27404. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27405. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27406. }
  27407. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27408. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27409. }
  27410. if (this.renderTargetsEnabled) {
  27411. this._intermediateRendering = true;
  27412. if (this._renderTargets.length > 0) {
  27413. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27414. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27415. var renderTarget = this._renderTargets.data[renderIndex];
  27416. if (renderTarget._shouldRender()) {
  27417. this._renderId++;
  27418. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27419. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27420. }
  27421. }
  27422. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27423. this._renderId++;
  27424. }
  27425. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27426. var step = _a[_i];
  27427. step.action(this.activeCamera);
  27428. }
  27429. this._intermediateRendering = false;
  27430. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27431. }
  27432. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27433. // Prepare Frame
  27434. if (this.postProcessManager) {
  27435. this.postProcessManager._prepareFrame();
  27436. }
  27437. // Before Camera Draw
  27438. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27439. var step = _c[_b];
  27440. step.action(this.activeCamera);
  27441. }
  27442. // Render
  27443. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27444. this._renderingManager.render(null, null, true, true);
  27445. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27446. // After Camera Draw
  27447. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27448. var step = _e[_d];
  27449. step.action(this.activeCamera);
  27450. }
  27451. // Finalize frame
  27452. if (this.postProcessManager) {
  27453. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27454. }
  27455. // Reset some special arrays
  27456. this._renderTargets.reset();
  27457. this._alternateRendering = false;
  27458. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27459. };
  27460. Scene.prototype._processSubCameras = function (camera) {
  27461. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27462. this._renderForCamera(camera);
  27463. return;
  27464. }
  27465. // rig cameras
  27466. for (var index = 0; index < camera._rigCameras.length; index++) {
  27467. this._renderForCamera(camera._rigCameras[index], camera);
  27468. }
  27469. this.activeCamera = camera;
  27470. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27471. };
  27472. Scene.prototype._checkIntersections = function () {
  27473. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27474. var sourceMesh = this._meshesForIntersections.data[index];
  27475. if (!sourceMesh.actionManager) {
  27476. continue;
  27477. }
  27478. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27479. var action = sourceMesh.actionManager.actions[actionIndex];
  27480. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27481. var parameters = action.getTriggerParameter();
  27482. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27483. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27484. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27485. if (areIntersecting && currentIntersectionInProgress === -1) {
  27486. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27487. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27488. sourceMesh._intersectionsInProgress.push(otherMesh);
  27489. }
  27490. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27491. sourceMesh._intersectionsInProgress.push(otherMesh);
  27492. }
  27493. }
  27494. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27495. //They intersected, and now they don't.
  27496. //is this trigger an exit trigger? execute an event.
  27497. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27498. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27499. }
  27500. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27501. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27502. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27503. return otherMesh === parameterMesh;
  27504. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27505. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27506. }
  27507. }
  27508. }
  27509. }
  27510. }
  27511. };
  27512. /**
  27513. * Render the scene
  27514. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27515. */
  27516. Scene.prototype.render = function (updateCameras) {
  27517. if (updateCameras === void 0) { updateCameras = true; }
  27518. if (this.isDisposed) {
  27519. return;
  27520. }
  27521. // Register components that have been associated lately to the scene.
  27522. this._registerTransientComponents();
  27523. this._activeParticles.fetchNewFrame();
  27524. this._totalVertices.fetchNewFrame();
  27525. this._activeIndices.fetchNewFrame();
  27526. this._activeBones.fetchNewFrame();
  27527. this._meshesForIntersections.reset();
  27528. this.resetCachedMaterial();
  27529. this.onBeforeAnimationsObservable.notifyObservers(this);
  27530. // Actions
  27531. if (this.actionManager) {
  27532. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27533. }
  27534. //Simplification Queue
  27535. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27536. this.simplificationQueue.executeNext();
  27537. }
  27538. if (this._engine.isDeterministicLockStep()) {
  27539. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27540. var defaultFPS = (60.0 / 1000.0);
  27541. var defaultFrameTime = 1000 / 60; // frame time in MS
  27542. if (this._physicsEngine) {
  27543. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27544. }
  27545. var stepsTaken = 0;
  27546. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27547. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27548. internalSteps = Math.min(internalSteps, maxSubSteps);
  27549. do {
  27550. this.onBeforeStepObservable.notifyObservers(this);
  27551. // Animations
  27552. this._animationRatio = defaultFrameTime * defaultFPS;
  27553. this._animate();
  27554. this.onAfterAnimationsObservable.notifyObservers(this);
  27555. // Physics
  27556. if (this._physicsEngine) {
  27557. this.onBeforePhysicsObservable.notifyObservers(this);
  27558. this._physicsEngine._step(defaultFrameTime / 1000);
  27559. this.onAfterPhysicsObservable.notifyObservers(this);
  27560. }
  27561. this.onAfterStepObservable.notifyObservers(this);
  27562. this._currentStepId++;
  27563. stepsTaken++;
  27564. deltaTime -= defaultFrameTime;
  27565. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27566. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27567. }
  27568. else {
  27569. // Animations
  27570. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27571. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27572. this._animate();
  27573. this.onAfterAnimationsObservable.notifyObservers(this);
  27574. // Physics
  27575. if (this._physicsEngine) {
  27576. this.onBeforePhysicsObservable.notifyObservers(this);
  27577. this._physicsEngine._step(deltaTime / 1000.0);
  27578. this.onAfterPhysicsObservable.notifyObservers(this);
  27579. }
  27580. }
  27581. // Before camera update steps
  27582. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27583. var step = _a[_i];
  27584. step.action();
  27585. }
  27586. // Update Cameras
  27587. if (updateCameras) {
  27588. if (this.activeCameras.length > 0) {
  27589. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27590. var camera = this.activeCameras[cameraIndex];
  27591. camera.update();
  27592. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27593. // rig cameras
  27594. for (var index = 0; index < camera._rigCameras.length; index++) {
  27595. camera._rigCameras[index].update();
  27596. }
  27597. }
  27598. }
  27599. }
  27600. else if (this.activeCamera) {
  27601. this.activeCamera.update();
  27602. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27603. // rig cameras
  27604. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27605. this.activeCamera._rigCameras[index].update();
  27606. }
  27607. }
  27608. }
  27609. }
  27610. // Before render
  27611. this.onBeforeRenderObservable.notifyObservers(this);
  27612. // Customs render targets
  27613. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27614. var engine = this.getEngine();
  27615. var currentActiveCamera = this.activeCamera;
  27616. if (this.renderTargetsEnabled) {
  27617. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27618. this._intermediateRendering = true;
  27619. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27620. var renderTarget = this.customRenderTargets[customIndex];
  27621. if (renderTarget._shouldRender()) {
  27622. this._renderId++;
  27623. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27624. if (!this.activeCamera)
  27625. throw new Error("Active camera not set");
  27626. // Viewport
  27627. engine.setViewport(this.activeCamera.viewport);
  27628. // Camera
  27629. this.updateTransformMatrix();
  27630. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27631. }
  27632. }
  27633. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27634. this._intermediateRendering = false;
  27635. this._renderId++;
  27636. }
  27637. // Restore back buffer
  27638. if (this.customRenderTargets.length > 0) {
  27639. engine.restoreDefaultFramebuffer();
  27640. }
  27641. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27642. this.activeCamera = currentActiveCamera;
  27643. // Procedural textures
  27644. if (this.proceduralTexturesEnabled) {
  27645. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27646. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27647. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27648. if (proceduralTexture._shouldRender()) {
  27649. proceduralTexture.render();
  27650. }
  27651. }
  27652. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27653. }
  27654. // Clear
  27655. if (this.autoClearDepthAndStencil || this.autoClear) {
  27656. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27657. }
  27658. // Shadows
  27659. if (this.shadowsEnabled) {
  27660. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27661. var light = this.lights[lightIndex];
  27662. var shadowGenerator = light.getShadowGenerator();
  27663. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27664. var shadowMap = (shadowGenerator.getShadowMap());
  27665. if (this.textures.indexOf(shadowMap) !== -1) {
  27666. this._renderTargets.push(shadowMap);
  27667. }
  27668. }
  27669. }
  27670. }
  27671. // Depth renderer
  27672. for (var key in this._depthRenderer) {
  27673. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27674. }
  27675. // Geometry renderer
  27676. if (this._geometryBufferRenderer) {
  27677. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27678. }
  27679. // RenderPipeline
  27680. if (this._postProcessRenderPipelineManager) {
  27681. this._postProcessRenderPipelineManager.update();
  27682. }
  27683. // Multi-cameras?
  27684. if (this.activeCameras.length > 0) {
  27685. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27686. if (cameraIndex > 0) {
  27687. this._engine.clear(null, false, true, true);
  27688. }
  27689. this._processSubCameras(this.activeCameras[cameraIndex]);
  27690. }
  27691. }
  27692. else {
  27693. if (!this.activeCamera) {
  27694. throw new Error("No camera defined");
  27695. }
  27696. this._processSubCameras(this.activeCamera);
  27697. }
  27698. // Intersection checks
  27699. this._checkIntersections();
  27700. // Update the audio listener attached to the camera
  27701. if (BABYLON.AudioEngine) {
  27702. this._updateAudioParameters();
  27703. }
  27704. // After render
  27705. if (this.afterRender) {
  27706. this.afterRender();
  27707. }
  27708. this.onAfterRenderObservable.notifyObservers(this);
  27709. // Cleaning
  27710. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27711. var data = this._toBeDisposed.data[index];
  27712. if (data) {
  27713. data.dispose();
  27714. }
  27715. this._toBeDisposed[index] = null;
  27716. }
  27717. this._toBeDisposed.reset();
  27718. if (this.dumpNextRenderTargets) {
  27719. this.dumpNextRenderTargets = false;
  27720. }
  27721. this._activeBones.addCount(0, true);
  27722. this._activeIndices.addCount(0, true);
  27723. this._activeParticles.addCount(0, true);
  27724. };
  27725. Scene.prototype._updateAudioParameters = function () {
  27726. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27727. return;
  27728. }
  27729. var listeningCamera;
  27730. var audioEngine = BABYLON.Engine.audioEngine;
  27731. if (this.activeCameras.length > 0) {
  27732. listeningCamera = this.activeCameras[0];
  27733. }
  27734. else {
  27735. listeningCamera = this.activeCamera;
  27736. }
  27737. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27738. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27739. // for VR cameras
  27740. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27741. listeningCamera = listeningCamera.rigCameras[0];
  27742. }
  27743. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27744. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27745. cameraDirection.normalize();
  27746. // To avoid some errors on GearVR
  27747. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27748. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27749. }
  27750. var i;
  27751. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27752. var sound = this.mainSoundTrack.soundCollection[i];
  27753. if (sound.useCustomAttenuation) {
  27754. sound.updateDistanceFromListener();
  27755. }
  27756. }
  27757. for (i = 0; i < this.soundTracks.length; i++) {
  27758. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27759. sound = this.soundTracks[i].soundCollection[j];
  27760. if (sound.useCustomAttenuation) {
  27761. sound.updateDistanceFromListener();
  27762. }
  27763. }
  27764. }
  27765. }
  27766. };
  27767. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27768. // Audio
  27769. /**
  27770. * Gets or sets if audio support is enabled
  27771. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27772. */
  27773. get: function () {
  27774. return this._audioEnabled;
  27775. },
  27776. set: function (value) {
  27777. this._audioEnabled = value;
  27778. if (BABYLON.AudioEngine) {
  27779. if (this._audioEnabled) {
  27780. this._enableAudio();
  27781. }
  27782. else {
  27783. this._disableAudio();
  27784. }
  27785. }
  27786. },
  27787. enumerable: true,
  27788. configurable: true
  27789. });
  27790. Scene.prototype._disableAudio = function () {
  27791. var i;
  27792. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27793. this.mainSoundTrack.soundCollection[i].pause();
  27794. }
  27795. for (i = 0; i < this.soundTracks.length; i++) {
  27796. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27797. this.soundTracks[i].soundCollection[j].pause();
  27798. }
  27799. }
  27800. };
  27801. Scene.prototype._enableAudio = function () {
  27802. var i;
  27803. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27804. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27805. this.mainSoundTrack.soundCollection[i].play();
  27806. }
  27807. }
  27808. for (i = 0; i < this.soundTracks.length; i++) {
  27809. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27810. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27811. this.soundTracks[i].soundCollection[j].play();
  27812. }
  27813. }
  27814. }
  27815. };
  27816. Object.defineProperty(Scene.prototype, "headphone", {
  27817. /**
  27818. * Gets or sets if audio will be output to headphones
  27819. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27820. */
  27821. get: function () {
  27822. return this._headphone;
  27823. },
  27824. set: function (value) {
  27825. this._headphone = value;
  27826. if (BABYLON.AudioEngine) {
  27827. if (this._headphone) {
  27828. this._switchAudioModeForHeadphones();
  27829. }
  27830. else {
  27831. this._switchAudioModeForNormalSpeakers();
  27832. }
  27833. }
  27834. },
  27835. enumerable: true,
  27836. configurable: true
  27837. });
  27838. Scene.prototype._switchAudioModeForHeadphones = function () {
  27839. this.mainSoundTrack.switchPanningModelToHRTF();
  27840. for (var i = 0; i < this.soundTracks.length; i++) {
  27841. this.soundTracks[i].switchPanningModelToHRTF();
  27842. }
  27843. };
  27844. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27845. this.mainSoundTrack.switchPanningModelToEqualPower();
  27846. for (var i = 0; i < this.soundTracks.length; i++) {
  27847. this.soundTracks[i].switchPanningModelToEqualPower();
  27848. }
  27849. };
  27850. /**
  27851. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27852. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27853. * @returns the created depth renderer
  27854. */
  27855. Scene.prototype.enableDepthRenderer = function (camera) {
  27856. camera = camera || this.activeCamera;
  27857. if (!camera) {
  27858. throw "No camera available to enable depth renderer";
  27859. }
  27860. if (!this._depthRenderer[camera.id]) {
  27861. var textureType = 0;
  27862. if (this._engine.getCaps().textureHalfFloatRender) {
  27863. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27864. }
  27865. else if (this._engine.getCaps().textureFloatRender) {
  27866. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27867. }
  27868. else {
  27869. throw "Depth renderer does not support int texture type";
  27870. }
  27871. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27872. }
  27873. return this._depthRenderer[camera.id];
  27874. };
  27875. /**
  27876. * Disables a depth renderer for a given camera
  27877. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27878. */
  27879. Scene.prototype.disableDepthRenderer = function (camera) {
  27880. camera = camera || this.activeCamera;
  27881. if (!camera || !this._depthRenderer[camera.id]) {
  27882. return;
  27883. }
  27884. this._depthRenderer[camera.id].dispose();
  27885. delete this._depthRenderer[camera.id];
  27886. };
  27887. /**
  27888. * Enables a GeometryBufferRender and associates it with the scene
  27889. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27890. * @returns the GeometryBufferRenderer
  27891. */
  27892. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27893. if (ratio === void 0) { ratio = 1; }
  27894. if (this._geometryBufferRenderer) {
  27895. return this._geometryBufferRenderer;
  27896. }
  27897. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27898. if (!this._geometryBufferRenderer.isSupported) {
  27899. this._geometryBufferRenderer = null;
  27900. }
  27901. return this._geometryBufferRenderer;
  27902. };
  27903. /**
  27904. * Disables the GeometryBufferRender associated with the scene
  27905. */
  27906. Scene.prototype.disableGeometryBufferRenderer = function () {
  27907. if (!this._geometryBufferRenderer) {
  27908. return;
  27909. }
  27910. this._geometryBufferRenderer.dispose();
  27911. this._geometryBufferRenderer = null;
  27912. };
  27913. /**
  27914. * Freeze all materials
  27915. * A frozen material will not be updatable but should be faster to render
  27916. */
  27917. Scene.prototype.freezeMaterials = function () {
  27918. for (var i = 0; i < this.materials.length; i++) {
  27919. this.materials[i].freeze();
  27920. }
  27921. };
  27922. /**
  27923. * Unfreeze all materials
  27924. * A frozen material will not be updatable but should be faster to render
  27925. */
  27926. Scene.prototype.unfreezeMaterials = function () {
  27927. for (var i = 0; i < this.materials.length; i++) {
  27928. this.materials[i].unfreeze();
  27929. }
  27930. };
  27931. /**
  27932. * Releases all held ressources
  27933. */
  27934. Scene.prototype.dispose = function () {
  27935. this.beforeRender = null;
  27936. this.afterRender = null;
  27937. this.skeletons = [];
  27938. this.morphTargetManagers = [];
  27939. this._transientComponents = [];
  27940. this._isReadyForMeshStage.clear();
  27941. this._beforeEvaluateActiveMeshStage.clear();
  27942. this._evaluateSubMeshStage.clear();
  27943. this._activeMeshStage.clear();
  27944. this._cameraDrawRenderTargetStage.clear();
  27945. this._beforeCameraDrawStage.clear();
  27946. this._beforeRenderingGroupDrawStage.clear();
  27947. this._afterRenderingGroupDrawStage.clear();
  27948. this._afterCameraDrawStage.clear();
  27949. this._beforeCameraUpdateStage.clear();
  27950. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27951. var component = _a[_i];
  27952. component.dispose();
  27953. }
  27954. this.importedMeshesFiles = new Array();
  27955. this.stopAllAnimations();
  27956. this.resetCachedMaterial();
  27957. for (var key in this._depthRenderer) {
  27958. this._depthRenderer[key].dispose();
  27959. }
  27960. // Smart arrays
  27961. if (this.activeCamera) {
  27962. this.activeCamera._activeMeshes.dispose();
  27963. this.activeCamera = null;
  27964. }
  27965. this._activeMeshes.dispose();
  27966. this._renderingManager.dispose();
  27967. this._processedMaterials.dispose();
  27968. this._activeParticleSystems.dispose();
  27969. this._activeSkeletons.dispose();
  27970. this._softwareSkinnedMeshes.dispose();
  27971. this._renderTargets.dispose();
  27972. this._registeredForLateAnimationBindings.dispose();
  27973. this._meshesForIntersections.dispose();
  27974. this._toBeDisposed.dispose();
  27975. // Abort active requests
  27976. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27977. var request = _c[_b];
  27978. request.abort();
  27979. }
  27980. // Debug layer
  27981. if (this._debugLayer) {
  27982. this._debugLayer.hide();
  27983. }
  27984. // Events
  27985. this.onDisposeObservable.notifyObservers(this);
  27986. this.onDisposeObservable.clear();
  27987. this.onBeforeRenderObservable.clear();
  27988. this.onAfterRenderObservable.clear();
  27989. this.onBeforeRenderTargetsRenderObservable.clear();
  27990. this.onAfterRenderTargetsRenderObservable.clear();
  27991. this.onAfterStepObservable.clear();
  27992. this.onBeforeStepObservable.clear();
  27993. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27994. this.onAfterActiveMeshesEvaluationObservable.clear();
  27995. this.onBeforeParticlesRenderingObservable.clear();
  27996. this.onAfterParticlesRenderingObservable.clear();
  27997. this.onBeforeSpritesRenderingObservable.clear();
  27998. this.onAfterSpritesRenderingObservable.clear();
  27999. this.onBeforeDrawPhaseObservable.clear();
  28000. this.onAfterDrawPhaseObservable.clear();
  28001. this.onBeforePhysicsObservable.clear();
  28002. this.onAfterPhysicsObservable.clear();
  28003. this.onBeforeAnimationsObservable.clear();
  28004. this.onAfterAnimationsObservable.clear();
  28005. this.onDataLoadedObservable.clear();
  28006. this.detachControl();
  28007. // Release sounds & sounds tracks
  28008. if (BABYLON.AudioEngine) {
  28009. this.disposeSounds();
  28010. }
  28011. // VR Helper
  28012. if (this.VRHelper) {
  28013. this.VRHelper.dispose();
  28014. }
  28015. // Detach cameras
  28016. var canvas = this._engine.getRenderingCanvas();
  28017. if (canvas) {
  28018. var index;
  28019. for (index = 0; index < this.cameras.length; index++) {
  28020. this.cameras[index].detachControl(canvas);
  28021. }
  28022. }
  28023. // Release animation groups
  28024. while (this.animationGroups.length) {
  28025. this.animationGroups[0].dispose();
  28026. }
  28027. // Release lights
  28028. while (this.lights.length) {
  28029. this.lights[0].dispose();
  28030. }
  28031. // Release meshes
  28032. while (this.meshes.length) {
  28033. this.meshes[0].dispose(true);
  28034. }
  28035. while (this.transformNodes.length) {
  28036. this.removeTransformNode(this.transformNodes[0]);
  28037. }
  28038. // Release cameras
  28039. while (this.cameras.length) {
  28040. this.cameras[0].dispose();
  28041. }
  28042. // Release materials
  28043. if (this.defaultMaterial) {
  28044. this.defaultMaterial.dispose();
  28045. }
  28046. while (this.multiMaterials.length) {
  28047. this.multiMaterials[0].dispose();
  28048. }
  28049. while (this.materials.length) {
  28050. this.materials[0].dispose();
  28051. }
  28052. // Release particles
  28053. while (this.particleSystems.length) {
  28054. this.particleSystems[0].dispose();
  28055. }
  28056. // Release sprites
  28057. while (this.spriteManagers.length) {
  28058. this.spriteManagers[0].dispose();
  28059. }
  28060. // Release postProcesses
  28061. while (this.postProcesses.length) {
  28062. this.postProcesses[0].dispose();
  28063. }
  28064. // Release textures
  28065. while (this.textures.length) {
  28066. this.textures[0].dispose();
  28067. }
  28068. // Release UBO
  28069. this._sceneUbo.dispose();
  28070. if (this._alternateSceneUbo) {
  28071. this._alternateSceneUbo.dispose();
  28072. }
  28073. // Post-processes
  28074. this.postProcessManager.dispose();
  28075. if (this._postProcessRenderPipelineManager) {
  28076. this._postProcessRenderPipelineManager.dispose();
  28077. }
  28078. // Physics
  28079. if (this._physicsEngine) {
  28080. this.disablePhysicsEngine();
  28081. }
  28082. // Remove from engine
  28083. index = this._engine.scenes.indexOf(this);
  28084. if (index > -1) {
  28085. this._engine.scenes.splice(index, 1);
  28086. }
  28087. this._engine.wipeCaches(true);
  28088. this._isDisposed = true;
  28089. };
  28090. Object.defineProperty(Scene.prototype, "isDisposed", {
  28091. /**
  28092. * Gets if the scene is already disposed
  28093. */
  28094. get: function () {
  28095. return this._isDisposed;
  28096. },
  28097. enumerable: true,
  28098. configurable: true
  28099. });
  28100. /**
  28101. * Releases sounds & soundtracks
  28102. */
  28103. Scene.prototype.disposeSounds = function () {
  28104. if (!this._mainSoundTrack) {
  28105. return;
  28106. }
  28107. this.mainSoundTrack.dispose();
  28108. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28109. this.soundTracks[scIndex].dispose();
  28110. }
  28111. };
  28112. /**
  28113. * Call this function to reduce memory footprint of the scene.
  28114. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28115. */
  28116. Scene.prototype.clearCachedVertexData = function () {
  28117. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28118. var mesh = this.meshes[meshIndex];
  28119. var geometry = mesh.geometry;
  28120. if (geometry) {
  28121. geometry._indices = [];
  28122. for (var vbName in geometry._vertexBuffers) {
  28123. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28124. continue;
  28125. }
  28126. geometry._vertexBuffers[vbName]._buffer._data = null;
  28127. }
  28128. }
  28129. }
  28130. };
  28131. /**
  28132. * This function will remove the local cached buffer data from texture.
  28133. * It will save memory but will prevent the texture from being rebuilt
  28134. */
  28135. Scene.prototype.cleanCachedTextureBuffer = function () {
  28136. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28137. var baseTexture = _a[_i];
  28138. var buffer = baseTexture._buffer;
  28139. if (buffer) {
  28140. baseTexture._buffer = null;
  28141. }
  28142. }
  28143. };
  28144. // Octrees
  28145. /**
  28146. * Get the world extend vectors with an optional filter
  28147. *
  28148. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28149. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28150. */
  28151. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28152. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28153. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28154. filterPredicate = filterPredicate || (function () { return true; });
  28155. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28156. mesh.computeWorldMatrix(true);
  28157. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28158. return;
  28159. }
  28160. var boundingInfo = mesh.getBoundingInfo();
  28161. var minBox = boundingInfo.boundingBox.minimumWorld;
  28162. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28163. BABYLON.Tools.CheckExtends(minBox, min, max);
  28164. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28165. });
  28166. return {
  28167. min: min,
  28168. max: max
  28169. };
  28170. };
  28171. /**
  28172. * Creates or updates the octree used to boost selection (picking)
  28173. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28174. * @param maxCapacity defines the maximum capacity per leaf
  28175. * @param maxDepth defines the maximum depth of the octree
  28176. * @returns an octree of AbstractMesh
  28177. */
  28178. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28179. if (maxCapacity === void 0) { maxCapacity = 64; }
  28180. if (maxDepth === void 0) { maxDepth = 2; }
  28181. if (!this._selectionOctree) {
  28182. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28183. }
  28184. var worldExtends = this.getWorldExtends();
  28185. // Update octree
  28186. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28187. return this._selectionOctree;
  28188. };
  28189. // Picking
  28190. /**
  28191. * Creates a ray that can be used to pick in the scene
  28192. * @param x defines the x coordinate of the origin (on-screen)
  28193. * @param y defines the y coordinate of the origin (on-screen)
  28194. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28195. * @param camera defines the camera to use for the picking
  28196. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28197. * @returns a Ray
  28198. */
  28199. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28200. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28201. var result = BABYLON.Ray.Zero();
  28202. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28203. return result;
  28204. };
  28205. /**
  28206. * Creates a ray that can be used to pick in the scene
  28207. * @param x defines the x coordinate of the origin (on-screen)
  28208. * @param y defines the y coordinate of the origin (on-screen)
  28209. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28210. * @param result defines the ray where to store the picking ray
  28211. * @param camera defines the camera to use for the picking
  28212. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28213. * @returns the current scene
  28214. */
  28215. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28216. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28217. var engine = this._engine;
  28218. if (!camera) {
  28219. if (!this.activeCamera)
  28220. throw new Error("Active camera not set");
  28221. camera = this.activeCamera;
  28222. }
  28223. var cameraViewport = camera.viewport;
  28224. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28225. // Moving coordinates to local viewport world
  28226. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28227. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28228. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28229. return this;
  28230. };
  28231. /**
  28232. * Creates a ray that can be used to pick in the scene
  28233. * @param x defines the x coordinate of the origin (on-screen)
  28234. * @param y defines the y coordinate of the origin (on-screen)
  28235. * @param camera defines the camera to use for the picking
  28236. * @returns a Ray
  28237. */
  28238. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28239. var result = BABYLON.Ray.Zero();
  28240. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28241. return result;
  28242. };
  28243. /**
  28244. * Creates a ray that can be used to pick in the scene
  28245. * @param x defines the x coordinate of the origin (on-screen)
  28246. * @param y defines the y coordinate of the origin (on-screen)
  28247. * @param result defines the ray where to store the picking ray
  28248. * @param camera defines the camera to use for the picking
  28249. * @returns the current scene
  28250. */
  28251. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28252. if (!BABYLON.PickingInfo) {
  28253. return this;
  28254. }
  28255. var engine = this._engine;
  28256. if (!camera) {
  28257. if (!this.activeCamera)
  28258. throw new Error("Active camera not set");
  28259. camera = this.activeCamera;
  28260. }
  28261. var cameraViewport = camera.viewport;
  28262. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28263. var identity = BABYLON.Matrix.Identity();
  28264. // Moving coordinates to local viewport world
  28265. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28266. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28267. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28268. return this;
  28269. };
  28270. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28271. if (!BABYLON.PickingInfo) {
  28272. return null;
  28273. }
  28274. var pickingInfo = null;
  28275. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28276. var mesh = this.meshes[meshIndex];
  28277. if (predicate) {
  28278. if (!predicate(mesh)) {
  28279. continue;
  28280. }
  28281. }
  28282. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28283. continue;
  28284. }
  28285. var world = mesh.getWorldMatrix();
  28286. var ray = rayFunction(world);
  28287. var result = mesh.intersects(ray, fastCheck);
  28288. if (!result || !result.hit)
  28289. continue;
  28290. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28291. continue;
  28292. pickingInfo = result;
  28293. if (fastCheck) {
  28294. break;
  28295. }
  28296. }
  28297. return pickingInfo || new BABYLON.PickingInfo();
  28298. };
  28299. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28300. if (!BABYLON.PickingInfo) {
  28301. return null;
  28302. }
  28303. var pickingInfos = new Array();
  28304. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28305. var mesh = this.meshes[meshIndex];
  28306. if (predicate) {
  28307. if (!predicate(mesh)) {
  28308. continue;
  28309. }
  28310. }
  28311. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28312. continue;
  28313. }
  28314. var world = mesh.getWorldMatrix();
  28315. var ray = rayFunction(world);
  28316. var result = mesh.intersects(ray, false);
  28317. if (!result || !result.hit)
  28318. continue;
  28319. pickingInfos.push(result);
  28320. }
  28321. return pickingInfos;
  28322. };
  28323. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28324. if (!BABYLON.PickingInfo) {
  28325. return null;
  28326. }
  28327. var pickingInfo = null;
  28328. if (!camera) {
  28329. if (!this.activeCamera) {
  28330. return null;
  28331. }
  28332. camera = this.activeCamera;
  28333. }
  28334. if (this.spriteManagers.length > 0) {
  28335. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28336. var spriteManager = this.spriteManagers[spriteIndex];
  28337. if (!spriteManager.isPickable) {
  28338. continue;
  28339. }
  28340. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28341. if (!result || !result.hit)
  28342. continue;
  28343. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28344. continue;
  28345. pickingInfo = result;
  28346. if (fastCheck) {
  28347. break;
  28348. }
  28349. }
  28350. }
  28351. return pickingInfo || new BABYLON.PickingInfo();
  28352. };
  28353. /** Launch a ray to try to pick a mesh in the scene
  28354. * @param x position on screen
  28355. * @param y position on screen
  28356. * @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
  28357. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28358. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28359. * @returns a PickingInfo
  28360. */
  28361. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28362. var _this = this;
  28363. if (!BABYLON.PickingInfo) {
  28364. return null;
  28365. }
  28366. var result = this._internalPick(function (world) {
  28367. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28368. return _this._tempPickingRay;
  28369. }, predicate, fastCheck);
  28370. if (result) {
  28371. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28372. }
  28373. return result;
  28374. };
  28375. /** Launch a ray to try to pick a sprite in the scene
  28376. * @param x position on screen
  28377. * @param y position on screen
  28378. * @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
  28379. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28380. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28381. * @returns a PickingInfo
  28382. */
  28383. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28384. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28385. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28386. };
  28387. /** Use the given ray to pick a mesh in the scene
  28388. * @param ray The ray to use to pick meshes
  28389. * @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
  28390. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28391. * @returns a PickingInfo
  28392. */
  28393. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28394. var _this = this;
  28395. var result = this._internalPick(function (world) {
  28396. if (!_this._pickWithRayInverseMatrix) {
  28397. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28398. }
  28399. world.invertToRef(_this._pickWithRayInverseMatrix);
  28400. if (!_this._cachedRayForTransform) {
  28401. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28402. }
  28403. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28404. return _this._cachedRayForTransform;
  28405. }, predicate, fastCheck);
  28406. if (result) {
  28407. result.ray = ray;
  28408. }
  28409. return result;
  28410. };
  28411. /**
  28412. * Launch a ray to try to pick a mesh in the scene
  28413. * @param x X position on screen
  28414. * @param y Y position on screen
  28415. * @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
  28416. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28417. * @returns an array of PickingInfo
  28418. */
  28419. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28420. var _this = this;
  28421. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28422. };
  28423. /**
  28424. * Launch a ray to try to pick a mesh in the scene
  28425. * @param ray Ray to use
  28426. * @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
  28427. * @returns an array of PickingInfo
  28428. */
  28429. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28430. var _this = this;
  28431. return this._internalMultiPick(function (world) {
  28432. if (!_this._pickWithRayInverseMatrix) {
  28433. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28434. }
  28435. world.invertToRef(_this._pickWithRayInverseMatrix);
  28436. if (!_this._cachedRayForTransform) {
  28437. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28438. }
  28439. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28440. return _this._cachedRayForTransform;
  28441. }, predicate);
  28442. };
  28443. /**
  28444. * Force the value of meshUnderPointer
  28445. * @param mesh defines the mesh to use
  28446. */
  28447. Scene.prototype.setPointerOverMesh = function (mesh) {
  28448. if (this._pointerOverMesh === mesh) {
  28449. return;
  28450. }
  28451. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28452. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28453. }
  28454. this._pointerOverMesh = mesh;
  28455. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28456. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28457. }
  28458. };
  28459. /**
  28460. * Gets the mesh under the pointer
  28461. * @returns a Mesh or null if no mesh is under the pointer
  28462. */
  28463. Scene.prototype.getPointerOverMesh = function () {
  28464. return this._pointerOverMesh;
  28465. };
  28466. /**
  28467. * Force the sprite under the pointer
  28468. * @param sprite defines the sprite to use
  28469. */
  28470. Scene.prototype.setPointerOverSprite = function (sprite) {
  28471. if (this._pointerOverSprite === sprite) {
  28472. return;
  28473. }
  28474. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28475. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28476. }
  28477. this._pointerOverSprite = sprite;
  28478. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28479. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28480. }
  28481. };
  28482. /**
  28483. * Gets the sprite under the pointer
  28484. * @returns a Sprite or null if no sprite is under the pointer
  28485. */
  28486. Scene.prototype.getPointerOverSprite = function () {
  28487. return this._pointerOverSprite;
  28488. };
  28489. // Physics
  28490. /**
  28491. * Gets the current physics engine
  28492. * @returns a PhysicsEngine or null if none attached
  28493. */
  28494. Scene.prototype.getPhysicsEngine = function () {
  28495. return this._physicsEngine;
  28496. };
  28497. /**
  28498. * Enables physics to the current scene
  28499. * @param gravity defines the scene's gravity for the physics engine
  28500. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28501. * @return a boolean indicating if the physics engine was initialized
  28502. */
  28503. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28504. if (gravity === void 0) { gravity = null; }
  28505. if (this._physicsEngine) {
  28506. return true;
  28507. }
  28508. try {
  28509. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28510. return true;
  28511. }
  28512. catch (e) {
  28513. BABYLON.Tools.Error(e.message);
  28514. return false;
  28515. }
  28516. };
  28517. /**
  28518. * Disables and disposes the physics engine associated with the scene
  28519. */
  28520. Scene.prototype.disablePhysicsEngine = function () {
  28521. if (!this._physicsEngine) {
  28522. return;
  28523. }
  28524. this._physicsEngine.dispose();
  28525. this._physicsEngine = null;
  28526. };
  28527. /**
  28528. * Gets a boolean indicating if there is an active physics engine
  28529. * @returns a boolean indicating if there is an active physics engine
  28530. */
  28531. Scene.prototype.isPhysicsEnabled = function () {
  28532. return this._physicsEngine !== undefined;
  28533. };
  28534. /**
  28535. * Deletes a physics compound impostor
  28536. * @param compound defines the compound to delete
  28537. */
  28538. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28539. var mesh = compound.parts[0].mesh;
  28540. if (mesh.physicsImpostor) {
  28541. mesh.physicsImpostor.dispose( /*true*/);
  28542. mesh.physicsImpostor = null;
  28543. }
  28544. };
  28545. // Misc.
  28546. /** @hidden */
  28547. Scene.prototype._rebuildGeometries = function () {
  28548. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28549. var geometry = _a[_i];
  28550. geometry._rebuild();
  28551. }
  28552. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28553. var mesh = _c[_b];
  28554. mesh._rebuild();
  28555. }
  28556. if (this.postProcessManager) {
  28557. this.postProcessManager._rebuild();
  28558. }
  28559. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28560. var component = _e[_d];
  28561. component.rebuild();
  28562. }
  28563. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28564. var system = _g[_f];
  28565. system.rebuild();
  28566. }
  28567. if (this._postProcessRenderPipelineManager) {
  28568. this._postProcessRenderPipelineManager._rebuild();
  28569. }
  28570. };
  28571. /** @hidden */
  28572. Scene.prototype._rebuildTextures = function () {
  28573. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28574. var texture = _a[_i];
  28575. texture._rebuild();
  28576. }
  28577. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28578. };
  28579. /**
  28580. * Creates a default light for the scene.
  28581. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28582. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28583. */
  28584. Scene.prototype.createDefaultLight = function (replace) {
  28585. if (replace === void 0) { replace = false; }
  28586. // Dispose existing light in replace mode.
  28587. if (replace) {
  28588. if (this.lights) {
  28589. for (var i = 0; i < this.lights.length; i++) {
  28590. this.lights[i].dispose();
  28591. }
  28592. }
  28593. }
  28594. // Light
  28595. if (this.lights.length === 0) {
  28596. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28597. }
  28598. };
  28599. /**
  28600. * Creates a default camera for the scene.
  28601. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28602. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28603. * @param replace has default false, when true replaces the active camera in the scene
  28604. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28605. */
  28606. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28607. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28608. if (replace === void 0) { replace = false; }
  28609. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28610. // Dispose existing camera in replace mode.
  28611. if (replace) {
  28612. if (this.activeCamera) {
  28613. this.activeCamera.dispose();
  28614. this.activeCamera = null;
  28615. }
  28616. }
  28617. // Camera
  28618. if (!this.activeCamera) {
  28619. var worldExtends = this.getWorldExtends();
  28620. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28621. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28622. var camera;
  28623. var radius = worldSize.length() * 1.5;
  28624. // empty scene scenario!
  28625. if (!isFinite(radius)) {
  28626. radius = 1;
  28627. worldCenter.copyFromFloats(0, 0, 0);
  28628. }
  28629. if (createArcRotateCamera) {
  28630. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28631. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28632. arcRotateCamera.wheelPrecision = 100 / radius;
  28633. camera = arcRotateCamera;
  28634. }
  28635. else {
  28636. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28637. freeCamera.setTarget(worldCenter);
  28638. camera = freeCamera;
  28639. }
  28640. camera.minZ = radius * 0.01;
  28641. camera.maxZ = radius * 1000;
  28642. camera.speed = radius * 0.2;
  28643. this.activeCamera = camera;
  28644. var canvas = this.getEngine().getRenderingCanvas();
  28645. if (attachCameraControls && canvas) {
  28646. camera.attachControl(canvas);
  28647. }
  28648. }
  28649. };
  28650. /**
  28651. * Creates a default camera and a default light.
  28652. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28653. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28654. * @param replace has the default false, when true replaces the active camera/light in the scene
  28655. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28656. */
  28657. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28658. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28659. if (replace === void 0) { replace = false; }
  28660. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28661. this.createDefaultLight(replace);
  28662. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28663. };
  28664. /**
  28665. * Creates a new sky box
  28666. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28667. * @param environmentTexture defines the texture to use as environment texture
  28668. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28669. * @param scale defines the overall scale of the skybox
  28670. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28671. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28672. * @returns a new mesh holding the sky box
  28673. */
  28674. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28675. if (pbr === void 0) { pbr = false; }
  28676. if (scale === void 0) { scale = 1000; }
  28677. if (blur === void 0) { blur = 0; }
  28678. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28679. if (!environmentTexture) {
  28680. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28681. return null;
  28682. }
  28683. if (setGlobalEnvTexture) {
  28684. if (environmentTexture) {
  28685. this.environmentTexture = environmentTexture;
  28686. }
  28687. }
  28688. // Skybox
  28689. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28690. if (pbr) {
  28691. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28692. hdrSkyboxMaterial.backFaceCulling = false;
  28693. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28694. if (hdrSkyboxMaterial.reflectionTexture) {
  28695. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28696. }
  28697. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28698. hdrSkyboxMaterial.disableLighting = true;
  28699. hdrSkyboxMaterial.twoSidedLighting = true;
  28700. hdrSkybox.infiniteDistance = true;
  28701. hdrSkybox.material = hdrSkyboxMaterial;
  28702. }
  28703. else {
  28704. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28705. skyboxMaterial.backFaceCulling = false;
  28706. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28707. if (skyboxMaterial.reflectionTexture) {
  28708. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28709. }
  28710. skyboxMaterial.disableLighting = true;
  28711. hdrSkybox.infiniteDistance = true;
  28712. hdrSkybox.material = skyboxMaterial;
  28713. }
  28714. return hdrSkybox;
  28715. };
  28716. /**
  28717. * Creates a new environment
  28718. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28719. * @param options defines the options you can use to configure the environment
  28720. * @returns the new EnvironmentHelper
  28721. */
  28722. Scene.prototype.createDefaultEnvironment = function (options) {
  28723. if (BABYLON.EnvironmentHelper) {
  28724. return new BABYLON.EnvironmentHelper(options, this);
  28725. }
  28726. return null;
  28727. };
  28728. /**
  28729. * Creates a new VREXperienceHelper
  28730. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28731. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28732. * @returns a new VREXperienceHelper
  28733. */
  28734. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28735. if (webVROptions === void 0) { webVROptions = {}; }
  28736. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28737. };
  28738. // Tags
  28739. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28740. if (tagsQuery === undefined) {
  28741. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28742. return list;
  28743. }
  28744. var listByTags = [];
  28745. forEach = forEach || (function (item) { return; });
  28746. for (var i in list) {
  28747. var item = list[i];
  28748. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28749. listByTags.push(item);
  28750. forEach(item);
  28751. }
  28752. }
  28753. return listByTags;
  28754. };
  28755. /**
  28756. * Get a list of meshes by tags
  28757. * @param tagsQuery defines the tags query to use
  28758. * @param forEach defines a predicate used to filter results
  28759. * @returns an array of Mesh
  28760. */
  28761. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28762. return this._getByTags(this.meshes, tagsQuery, forEach);
  28763. };
  28764. /**
  28765. * Get a list of cameras by tags
  28766. * @param tagsQuery defines the tags query to use
  28767. * @param forEach defines a predicate used to filter results
  28768. * @returns an array of Camera
  28769. */
  28770. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28771. return this._getByTags(this.cameras, tagsQuery, forEach);
  28772. };
  28773. /**
  28774. * Get a list of lights by tags
  28775. * @param tagsQuery defines the tags query to use
  28776. * @param forEach defines a predicate used to filter results
  28777. * @returns an array of Light
  28778. */
  28779. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28780. return this._getByTags(this.lights, tagsQuery, forEach);
  28781. };
  28782. /**
  28783. * Get a list of materials by tags
  28784. * @param tagsQuery defines the tags query to use
  28785. * @param forEach defines a predicate used to filter results
  28786. * @returns an array of Material
  28787. */
  28788. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28789. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28790. };
  28791. /**
  28792. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28793. * This allowed control for front to back rendering or reversly depending of the special needs.
  28794. *
  28795. * @param renderingGroupId The rendering group id corresponding to its index
  28796. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28797. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28798. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28799. */
  28800. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28801. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28802. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28803. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28804. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28805. };
  28806. /**
  28807. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28808. *
  28809. * @param renderingGroupId The rendering group id corresponding to its index
  28810. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28811. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28812. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28813. */
  28814. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28815. if (depth === void 0) { depth = true; }
  28816. if (stencil === void 0) { stencil = true; }
  28817. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28818. };
  28819. /**
  28820. * Will flag all materials as dirty to trigger new shader compilation
  28821. * @param flag defines the flag used to specify which material part must be marked as dirty
  28822. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28823. */
  28824. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28825. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28826. var material = _a[_i];
  28827. if (predicate && !predicate(material)) {
  28828. continue;
  28829. }
  28830. material.markAsDirty(flag);
  28831. }
  28832. };
  28833. /** @hidden */
  28834. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28835. var _this = this;
  28836. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28837. this._activeRequests.push(request);
  28838. request.onCompleteObservable.add(function (request) {
  28839. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28840. });
  28841. return request;
  28842. };
  28843. /** @hidden */
  28844. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28845. var _this = this;
  28846. return new Promise(function (resolve, reject) {
  28847. _this._loadFile(url, function (data) {
  28848. resolve(data);
  28849. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28850. reject(exception);
  28851. });
  28852. });
  28853. };
  28854. // Statics
  28855. Scene._FOGMODE_NONE = 0;
  28856. Scene._FOGMODE_EXP = 1;
  28857. Scene._FOGMODE_EXP2 = 2;
  28858. Scene._FOGMODE_LINEAR = 3;
  28859. Scene._uniqueIdCounter = 0;
  28860. /**
  28861. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28862. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28863. */
  28864. Scene.MinDeltaTime = 1.0;
  28865. /**
  28866. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28867. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28868. */
  28869. Scene.MaxDeltaTime = 1000.0;
  28870. /** The distance in pixel that you have to move to prevent some events */
  28871. Scene.DragMovementThreshold = 10; // in pixels
  28872. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28873. Scene.LongPressDelay = 500; // in milliseconds
  28874. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28875. Scene.DoubleClickDelay = 300; // in milliseconds
  28876. /** If you need to check double click without raising a single click at first click, enable this flag */
  28877. Scene.ExclusiveDoubleClickMode = false;
  28878. return Scene;
  28879. }(BABYLON.AbstractScene));
  28880. BABYLON.Scene = Scene;
  28881. })(BABYLON || (BABYLON = {}));
  28882. //# sourceMappingURL=babylon.scene.js.map
  28883. var BABYLON;
  28884. (function (BABYLON) {
  28885. /**
  28886. * Set of assets to keep when moving a scene into an asset container.
  28887. */
  28888. var KeepAssets = /** @class */ (function (_super) {
  28889. __extends(KeepAssets, _super);
  28890. function KeepAssets() {
  28891. return _super !== null && _super.apply(this, arguments) || this;
  28892. }
  28893. return KeepAssets;
  28894. }(BABYLON.AbstractScene));
  28895. BABYLON.KeepAssets = KeepAssets;
  28896. /**
  28897. * Container with a set of assets that can be added or removed from a scene.
  28898. */
  28899. var AssetContainer = /** @class */ (function (_super) {
  28900. __extends(AssetContainer, _super);
  28901. /**
  28902. * Instantiates an AssetContainer.
  28903. * @param scene The scene the AssetContainer belongs to.
  28904. */
  28905. function AssetContainer(scene) {
  28906. var _this = _super.call(this) || this;
  28907. _this.scene = scene;
  28908. return _this;
  28909. }
  28910. /**
  28911. * Adds all the assets from the container to the scene.
  28912. */
  28913. AssetContainer.prototype.addAllToScene = function () {
  28914. var _this = this;
  28915. this.cameras.forEach(function (o) {
  28916. _this.scene.addCamera(o);
  28917. });
  28918. this.lights.forEach(function (o) {
  28919. _this.scene.addLight(o);
  28920. });
  28921. this.meshes.forEach(function (o) {
  28922. _this.scene.addMesh(o);
  28923. });
  28924. this.skeletons.forEach(function (o) {
  28925. _this.scene.addSkeleton(o);
  28926. });
  28927. this.animations.forEach(function (o) {
  28928. _this.scene.addAnimation(o);
  28929. });
  28930. this.animationGroups.forEach(function (o) {
  28931. _this.scene.addAnimationGroup(o);
  28932. });
  28933. this.multiMaterials.forEach(function (o) {
  28934. _this.scene.addMultiMaterial(o);
  28935. });
  28936. this.materials.forEach(function (o) {
  28937. _this.scene.addMaterial(o);
  28938. });
  28939. this.morphTargetManagers.forEach(function (o) {
  28940. _this.scene.addMorphTargetManager(o);
  28941. });
  28942. this.geometries.forEach(function (o) {
  28943. _this.scene.addGeometry(o);
  28944. });
  28945. this.transformNodes.forEach(function (o) {
  28946. _this.scene.addTransformNode(o);
  28947. });
  28948. this.actionManagers.forEach(function (o) {
  28949. _this.scene.addActionManager(o);
  28950. });
  28951. this.sounds.forEach(function (o) {
  28952. o.play();
  28953. o.autoplay = true;
  28954. _this.scene.mainSoundTrack.AddSound(o);
  28955. });
  28956. this.textures.forEach(function (o) {
  28957. _this.scene.addTexture(o);
  28958. });
  28959. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28960. var component = _a[_i];
  28961. component.addFromContainer(this.scene);
  28962. }
  28963. };
  28964. /**
  28965. * Removes all the assets in the container from the scene
  28966. */
  28967. AssetContainer.prototype.removeAllFromScene = function () {
  28968. var _this = this;
  28969. this.cameras.forEach(function (o) {
  28970. _this.scene.removeCamera(o);
  28971. });
  28972. this.lights.forEach(function (o) {
  28973. _this.scene.removeLight(o);
  28974. });
  28975. this.meshes.forEach(function (o) {
  28976. _this.scene.removeMesh(o);
  28977. });
  28978. this.skeletons.forEach(function (o) {
  28979. _this.scene.removeSkeleton(o);
  28980. });
  28981. this.animations.forEach(function (o) {
  28982. _this.scene.removeAnimation(o);
  28983. });
  28984. this.animationGroups.forEach(function (o) {
  28985. _this.scene.removeAnimationGroup(o);
  28986. });
  28987. this.multiMaterials.forEach(function (o) {
  28988. _this.scene.removeMultiMaterial(o);
  28989. });
  28990. this.materials.forEach(function (o) {
  28991. _this.scene.removeMaterial(o);
  28992. });
  28993. this.morphTargetManagers.forEach(function (o) {
  28994. _this.scene.removeMorphTargetManager(o);
  28995. });
  28996. this.geometries.forEach(function (o) {
  28997. _this.scene.removeGeometry(o);
  28998. });
  28999. this.transformNodes.forEach(function (o) {
  29000. _this.scene.removeTransformNode(o);
  29001. });
  29002. this.actionManagers.forEach(function (o) {
  29003. _this.scene.removeActionManager(o);
  29004. });
  29005. this.sounds.forEach(function (o) {
  29006. o.stop();
  29007. o.autoplay = false;
  29008. _this.scene.mainSoundTrack.RemoveSound(o);
  29009. });
  29010. this.textures.forEach(function (o) {
  29011. _this.scene.removeTexture(o);
  29012. });
  29013. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29014. var component = _a[_i];
  29015. component.removeFromContainer(this.scene);
  29016. }
  29017. };
  29018. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29019. if (!sourceAssets) {
  29020. return;
  29021. }
  29022. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29023. var asset = sourceAssets_1[_i];
  29024. var move = true;
  29025. if (keepAssets) {
  29026. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29027. var keepAsset = keepAssets_1[_a];
  29028. if (asset === keepAsset) {
  29029. move = false;
  29030. break;
  29031. }
  29032. }
  29033. }
  29034. if (move) {
  29035. targetAssets.push(asset);
  29036. }
  29037. }
  29038. };
  29039. /**
  29040. * Removes all the assets contained in the scene and adds them to the container.
  29041. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29042. */
  29043. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29044. if (keepAssets === undefined) {
  29045. keepAssets = new KeepAssets();
  29046. }
  29047. for (var key in this) {
  29048. if (this.hasOwnProperty(key)) {
  29049. this[key] = this[key] || [];
  29050. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29051. }
  29052. }
  29053. this.removeAllFromScene();
  29054. };
  29055. /**
  29056. * 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.
  29057. * @returns the root mesh
  29058. */
  29059. AssetContainer.prototype.createRootMesh = function () {
  29060. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29061. this.meshes.forEach(function (m) {
  29062. if (!m.parent) {
  29063. rootMesh.addChild(m);
  29064. }
  29065. });
  29066. this.meshes.unshift(rootMesh);
  29067. return rootMesh;
  29068. };
  29069. return AssetContainer;
  29070. }(BABYLON.AbstractScene));
  29071. BABYLON.AssetContainer = AssetContainer;
  29072. })(BABYLON || (BABYLON = {}));
  29073. //# sourceMappingURL=babylon.assetContainer.js.map
  29074. var BABYLON;
  29075. (function (BABYLON) {
  29076. var Buffer = /** @class */ (function () {
  29077. /**
  29078. * Constructor
  29079. * @param engine the engine
  29080. * @param data the data to use for this buffer
  29081. * @param updatable whether the data is updatable
  29082. * @param stride the stride (optional)
  29083. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29084. * @param instanced whether the buffer is instanced (optional)
  29085. * @param useBytes set to true if the stride in in bytes (optional)
  29086. */
  29087. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29088. if (stride === void 0) { stride = 0; }
  29089. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29090. if (instanced === void 0) { instanced = false; }
  29091. if (useBytes === void 0) { useBytes = false; }
  29092. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29093. this._engine = engine.getScene().getEngine();
  29094. }
  29095. else {
  29096. this._engine = engine;
  29097. }
  29098. this._updatable = updatable;
  29099. this._instanced = instanced;
  29100. this._data = data;
  29101. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29102. if (!postponeInternalCreation) { // by default
  29103. this.create();
  29104. }
  29105. }
  29106. /**
  29107. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29108. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29109. * @param offset defines offset in the buffer (0 by default)
  29110. * @param size defines the size in floats of attributes (position is 3 for instance)
  29111. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29112. * @param instanced defines if the vertex buffer contains indexed data
  29113. * @param useBytes defines if the offset and stride are in bytes
  29114. * @returns the new vertex buffer
  29115. */
  29116. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29117. if (useBytes === void 0) { useBytes = false; }
  29118. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29119. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29120. // a lot of these parameters are ignored as they are overriden by the buffer
  29121. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29122. };
  29123. // Properties
  29124. Buffer.prototype.isUpdatable = function () {
  29125. return this._updatable;
  29126. };
  29127. Buffer.prototype.getData = function () {
  29128. return this._data;
  29129. };
  29130. Buffer.prototype.getBuffer = function () {
  29131. return this._buffer;
  29132. };
  29133. /**
  29134. * Gets the stride in float32 units (i.e. byte stride / 4).
  29135. * May not be an integer if the byte stride is not divisible by 4.
  29136. * DEPRECATED. Use byteStride instead.
  29137. * @returns the stride in float32 units
  29138. */
  29139. Buffer.prototype.getStrideSize = function () {
  29140. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29141. };
  29142. // Methods
  29143. Buffer.prototype.create = function (data) {
  29144. if (data === void 0) { data = null; }
  29145. if (!data && this._buffer) {
  29146. return; // nothing to do
  29147. }
  29148. data = data || this._data;
  29149. if (!data) {
  29150. return;
  29151. }
  29152. if (!this._buffer) { // create buffer
  29153. if (this._updatable) {
  29154. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29155. this._data = data;
  29156. }
  29157. else {
  29158. this._buffer = this._engine.createVertexBuffer(data);
  29159. }
  29160. }
  29161. else if (this._updatable) { // update buffer
  29162. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29163. this._data = data;
  29164. }
  29165. };
  29166. Buffer.prototype._rebuild = function () {
  29167. this._buffer = null;
  29168. this.create(this._data);
  29169. };
  29170. Buffer.prototype.update = function (data) {
  29171. this.create(data);
  29172. };
  29173. /**
  29174. * Updates the data directly.
  29175. * @param data the new data
  29176. * @param offset the new offset
  29177. * @param vertexCount the vertex count (optional)
  29178. * @param useBytes set to true if the offset is in bytes
  29179. */
  29180. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29181. if (useBytes === void 0) { useBytes = false; }
  29182. if (!this._buffer) {
  29183. return;
  29184. }
  29185. if (this._updatable) { // update buffer
  29186. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29187. this._data = null;
  29188. }
  29189. };
  29190. Buffer.prototype.dispose = function () {
  29191. if (!this._buffer) {
  29192. return;
  29193. }
  29194. if (this._engine._releaseBuffer(this._buffer)) {
  29195. this._buffer = null;
  29196. }
  29197. };
  29198. return Buffer;
  29199. }());
  29200. BABYLON.Buffer = Buffer;
  29201. })(BABYLON || (BABYLON = {}));
  29202. //# sourceMappingURL=babylon.buffer.js.map
  29203. var BABYLON;
  29204. (function (BABYLON) {
  29205. var VertexBuffer = /** @class */ (function () {
  29206. /**
  29207. * Constructor
  29208. * @param engine the engine
  29209. * @param data the data to use for this vertex buffer
  29210. * @param kind the vertex buffer kind
  29211. * @param updatable whether the data is updatable
  29212. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29213. * @param stride the stride (optional)
  29214. * @param instanced whether the buffer is instanced (optional)
  29215. * @param offset the offset of the data (optional)
  29216. * @param size the number of components (optional)
  29217. * @param type the type of the component (optional)
  29218. * @param normalized whether the data contains normalized data (optional)
  29219. * @param useBytes set to true if stride and offset are in bytes (optional)
  29220. */
  29221. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29222. if (normalized === void 0) { normalized = false; }
  29223. if (useBytes === void 0) { useBytes = false; }
  29224. if (data instanceof BABYLON.Buffer) {
  29225. this._buffer = data;
  29226. this._ownsBuffer = false;
  29227. }
  29228. else {
  29229. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29230. this._ownsBuffer = true;
  29231. }
  29232. this._kind = kind;
  29233. if (type == undefined) {
  29234. var data_1 = this.getData();
  29235. this.type = VertexBuffer.FLOAT;
  29236. if (data_1 instanceof Int8Array)
  29237. this.type = VertexBuffer.BYTE;
  29238. else if (data_1 instanceof Uint8Array)
  29239. this.type = VertexBuffer.UNSIGNED_BYTE;
  29240. else if (data_1 instanceof Int16Array)
  29241. this.type = VertexBuffer.SHORT;
  29242. else if (data_1 instanceof Uint16Array)
  29243. this.type = VertexBuffer.UNSIGNED_SHORT;
  29244. else if (data_1 instanceof Int32Array)
  29245. this.type = VertexBuffer.INT;
  29246. else if (data_1 instanceof Uint32Array)
  29247. this.type = VertexBuffer.UNSIGNED_INT;
  29248. }
  29249. else {
  29250. this.type = type;
  29251. }
  29252. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29253. if (useBytes) {
  29254. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29255. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29256. this.byteOffset = offset || 0;
  29257. }
  29258. else {
  29259. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29260. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29261. this.byteOffset = (offset || 0) * typeByteLength;
  29262. }
  29263. this.normalized = normalized;
  29264. this._instanced = instanced !== undefined ? instanced : false;
  29265. this._instanceDivisor = instanced ? 1 : 0;
  29266. }
  29267. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29268. /**
  29269. * Gets or sets the instance divisor when in instanced mode
  29270. */
  29271. get: function () {
  29272. return this._instanceDivisor;
  29273. },
  29274. set: function (value) {
  29275. this._instanceDivisor = value;
  29276. if (value == 0) {
  29277. this._instanced = false;
  29278. }
  29279. else {
  29280. this._instanced = true;
  29281. }
  29282. },
  29283. enumerable: true,
  29284. configurable: true
  29285. });
  29286. VertexBuffer.prototype._rebuild = function () {
  29287. if (!this._buffer) {
  29288. return;
  29289. }
  29290. this._buffer._rebuild();
  29291. };
  29292. /**
  29293. * Returns the kind of the VertexBuffer (string).
  29294. */
  29295. VertexBuffer.prototype.getKind = function () {
  29296. return this._kind;
  29297. };
  29298. // Properties
  29299. /**
  29300. * Boolean : is the VertexBuffer updatable ?
  29301. */
  29302. VertexBuffer.prototype.isUpdatable = function () {
  29303. return this._buffer.isUpdatable();
  29304. };
  29305. /**
  29306. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29307. */
  29308. VertexBuffer.prototype.getData = function () {
  29309. return this._buffer.getData();
  29310. };
  29311. /**
  29312. * Returns the WebGLBuffer associated to the VertexBuffer.
  29313. */
  29314. VertexBuffer.prototype.getBuffer = function () {
  29315. return this._buffer.getBuffer();
  29316. };
  29317. /**
  29318. * Returns the stride as a multiple of the type byte length.
  29319. * DEPRECATED. Use byteStride instead.
  29320. */
  29321. VertexBuffer.prototype.getStrideSize = function () {
  29322. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29323. };
  29324. /**
  29325. * Returns the offset as a multiple of the type byte length.
  29326. * DEPRECATED. Use byteOffset instead.
  29327. */
  29328. VertexBuffer.prototype.getOffset = function () {
  29329. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29330. };
  29331. /**
  29332. * Returns the number of components per vertex attribute (integer).
  29333. */
  29334. VertexBuffer.prototype.getSize = function () {
  29335. return this._size;
  29336. };
  29337. /**
  29338. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29339. */
  29340. VertexBuffer.prototype.getIsInstanced = function () {
  29341. return this._instanced;
  29342. };
  29343. /**
  29344. * Returns the instancing divisor, zero for non-instanced (integer).
  29345. */
  29346. VertexBuffer.prototype.getInstanceDivisor = function () {
  29347. return this._instanceDivisor;
  29348. };
  29349. // Methods
  29350. /**
  29351. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29352. * Returns the created WebGLBuffer.
  29353. */
  29354. VertexBuffer.prototype.create = function (data) {
  29355. return this._buffer.create(data);
  29356. };
  29357. /**
  29358. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29359. * This function will create a new buffer if the current one is not updatable
  29360. * Returns the updated WebGLBuffer.
  29361. */
  29362. VertexBuffer.prototype.update = function (data) {
  29363. return this._buffer.update(data);
  29364. };
  29365. /**
  29366. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29367. * Returns the directly updated WebGLBuffer.
  29368. * @param data the new data
  29369. * @param offset the new offset
  29370. * @param useBytes set to true if the offset is in bytes
  29371. */
  29372. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29373. if (useBytes === void 0) { useBytes = false; }
  29374. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29375. };
  29376. /**
  29377. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29378. */
  29379. VertexBuffer.prototype.dispose = function () {
  29380. if (this._ownsBuffer) {
  29381. this._buffer.dispose();
  29382. }
  29383. };
  29384. /**
  29385. * Enumerates each value of this vertex buffer as numbers.
  29386. * @param count the number of values to enumerate
  29387. * @param callback the callback function called for each value
  29388. */
  29389. VertexBuffer.prototype.forEach = function (count, callback) {
  29390. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29391. };
  29392. Object.defineProperty(VertexBuffer, "PositionKind", {
  29393. get: function () {
  29394. return VertexBuffer._PositionKind;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(VertexBuffer, "NormalKind", {
  29400. get: function () {
  29401. return VertexBuffer._NormalKind;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(VertexBuffer, "TangentKind", {
  29407. get: function () {
  29408. return VertexBuffer._TangentKind;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(VertexBuffer, "UVKind", {
  29414. get: function () {
  29415. return VertexBuffer._UVKind;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29421. get: function () {
  29422. return VertexBuffer._UV2Kind;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29428. get: function () {
  29429. return VertexBuffer._UV3Kind;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29435. get: function () {
  29436. return VertexBuffer._UV4Kind;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29442. get: function () {
  29443. return VertexBuffer._UV5Kind;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29449. get: function () {
  29450. return VertexBuffer._UV6Kind;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. Object.defineProperty(VertexBuffer, "ColorKind", {
  29456. get: function () {
  29457. return VertexBuffer._ColorKind;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29463. get: function () {
  29464. return VertexBuffer._MatricesIndicesKind;
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29470. get: function () {
  29471. return VertexBuffer._MatricesWeightsKind;
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29477. get: function () {
  29478. return VertexBuffer._MatricesIndicesExtraKind;
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29484. get: function () {
  29485. return VertexBuffer._MatricesWeightsExtraKind;
  29486. },
  29487. enumerable: true,
  29488. configurable: true
  29489. });
  29490. /**
  29491. * Deduces the stride given a kind.
  29492. * @param kind The kind string to deduce
  29493. * @returns The deduced stride
  29494. */
  29495. VertexBuffer.DeduceStride = function (kind) {
  29496. switch (kind) {
  29497. case VertexBuffer.UVKind:
  29498. case VertexBuffer.UV2Kind:
  29499. case VertexBuffer.UV3Kind:
  29500. case VertexBuffer.UV4Kind:
  29501. case VertexBuffer.UV5Kind:
  29502. case VertexBuffer.UV6Kind:
  29503. return 2;
  29504. case VertexBuffer.NormalKind:
  29505. case VertexBuffer.PositionKind:
  29506. return 3;
  29507. case VertexBuffer.ColorKind:
  29508. case VertexBuffer.MatricesIndicesKind:
  29509. case VertexBuffer.MatricesIndicesExtraKind:
  29510. case VertexBuffer.MatricesWeightsKind:
  29511. case VertexBuffer.MatricesWeightsExtraKind:
  29512. case VertexBuffer.TangentKind:
  29513. return 4;
  29514. default:
  29515. throw new Error("Invalid kind '" + kind + "'");
  29516. }
  29517. };
  29518. /**
  29519. * Gets the byte length of the given type.
  29520. * @param type the type
  29521. * @returns the number of bytes
  29522. */
  29523. VertexBuffer.GetTypeByteLength = function (type) {
  29524. switch (type) {
  29525. case VertexBuffer.BYTE:
  29526. case VertexBuffer.UNSIGNED_BYTE:
  29527. return 1;
  29528. case VertexBuffer.SHORT:
  29529. case VertexBuffer.UNSIGNED_SHORT:
  29530. return 2;
  29531. case VertexBuffer.INT:
  29532. case VertexBuffer.FLOAT:
  29533. return 4;
  29534. default:
  29535. throw new Error("Invalid type '" + type + "'");
  29536. }
  29537. };
  29538. /**
  29539. * Enumerates each value of the given parameters as numbers.
  29540. * @param data the data to enumerate
  29541. * @param byteOffset the byte offset of the data
  29542. * @param byteStride the byte stride of the data
  29543. * @param componentCount the number of components per element
  29544. * @param componentType the type of the component
  29545. * @param count the total number of components
  29546. * @param normalized whether the data is normalized
  29547. * @param callback the callback function called for each value
  29548. */
  29549. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29550. if (data instanceof Array) {
  29551. var offset = byteOffset / 4;
  29552. var stride = byteStride / 4;
  29553. for (var index = 0; index < count; index += componentCount) {
  29554. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29555. callback(data[offset + componentIndex], index + componentIndex);
  29556. }
  29557. offset += stride;
  29558. }
  29559. }
  29560. else {
  29561. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29562. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29563. for (var index = 0; index < count; index += componentCount) {
  29564. var componentByteOffset = byteOffset;
  29565. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29566. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29567. callback(value, index + componentIndex);
  29568. componentByteOffset += componentByteLength;
  29569. }
  29570. byteOffset += byteStride;
  29571. }
  29572. }
  29573. };
  29574. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29575. switch (type) {
  29576. case VertexBuffer.BYTE: {
  29577. var value = dataView.getInt8(byteOffset);
  29578. if (normalized) {
  29579. value = Math.max(value / 127, -1);
  29580. }
  29581. return value;
  29582. }
  29583. case VertexBuffer.UNSIGNED_BYTE: {
  29584. var value = dataView.getUint8(byteOffset);
  29585. if (normalized) {
  29586. value = value / 255;
  29587. }
  29588. return value;
  29589. }
  29590. case VertexBuffer.SHORT: {
  29591. var value = dataView.getInt16(byteOffset, true);
  29592. if (normalized) {
  29593. value = Math.max(value / 16383, -1);
  29594. }
  29595. return value;
  29596. }
  29597. case VertexBuffer.UNSIGNED_SHORT: {
  29598. var value = dataView.getUint16(byteOffset, true);
  29599. if (normalized) {
  29600. value = value / 65535;
  29601. }
  29602. return value;
  29603. }
  29604. case VertexBuffer.FLOAT: {
  29605. return dataView.getFloat32(byteOffset, true);
  29606. }
  29607. default: {
  29608. throw new Error("Invalid component type " + type);
  29609. }
  29610. }
  29611. };
  29612. /**
  29613. * The byte type.
  29614. */
  29615. VertexBuffer.BYTE = 5120;
  29616. /**
  29617. * The unsigned byte type.
  29618. */
  29619. VertexBuffer.UNSIGNED_BYTE = 5121;
  29620. /**
  29621. * The short type.
  29622. */
  29623. VertexBuffer.SHORT = 5122;
  29624. /**
  29625. * The unsigned short type.
  29626. */
  29627. VertexBuffer.UNSIGNED_SHORT = 5123;
  29628. /**
  29629. * The integer type.
  29630. */
  29631. VertexBuffer.INT = 5124;
  29632. /**
  29633. * The unsigned integer type.
  29634. */
  29635. VertexBuffer.UNSIGNED_INT = 5125;
  29636. /**
  29637. * The float type.
  29638. */
  29639. VertexBuffer.FLOAT = 5126;
  29640. // Enums
  29641. VertexBuffer._PositionKind = "position";
  29642. VertexBuffer._NormalKind = "normal";
  29643. VertexBuffer._TangentKind = "tangent";
  29644. VertexBuffer._UVKind = "uv";
  29645. VertexBuffer._UV2Kind = "uv2";
  29646. VertexBuffer._UV3Kind = "uv3";
  29647. VertexBuffer._UV4Kind = "uv4";
  29648. VertexBuffer._UV5Kind = "uv5";
  29649. VertexBuffer._UV6Kind = "uv6";
  29650. VertexBuffer._ColorKind = "color";
  29651. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29652. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29653. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29654. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29655. return VertexBuffer;
  29656. }());
  29657. BABYLON.VertexBuffer = VertexBuffer;
  29658. })(BABYLON || (BABYLON = {}));
  29659. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29660. var BABYLON;
  29661. (function (BABYLON) {
  29662. /**
  29663. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29664. */
  29665. var DummyInternalTextureTracker = /** @class */ (function () {
  29666. function DummyInternalTextureTracker() {
  29667. /**
  29668. * Gets or set the previous tracker in the list
  29669. */
  29670. this.previous = null;
  29671. /**
  29672. * Gets or set the next tracker in the list
  29673. */
  29674. this.next = null;
  29675. }
  29676. return DummyInternalTextureTracker;
  29677. }());
  29678. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29679. })(BABYLON || (BABYLON = {}));
  29680. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29681. var BABYLON;
  29682. (function (BABYLON) {
  29683. /**
  29684. * Class used to store data associated with WebGL texture data for the engine
  29685. * This class should not be used directly
  29686. */
  29687. var InternalTexture = /** @class */ (function () {
  29688. /**
  29689. * Creates a new InternalTexture
  29690. * @param engine defines the engine to use
  29691. * @param dataSource defines the type of data that will be used
  29692. */
  29693. function InternalTexture(engine, dataSource) {
  29694. /**
  29695. * Observable called when the texture is loaded
  29696. */
  29697. this.onLoadedObservable = new BABYLON.Observable();
  29698. /**
  29699. * Gets or set the previous tracker in the list
  29700. */
  29701. this.previous = null;
  29702. /**
  29703. * Gets or set the next tracker in the list
  29704. */
  29705. this.next = null;
  29706. // Private
  29707. /** @hidden */
  29708. this._initialSlot = -1;
  29709. /** @hidden */
  29710. this._designatedSlot = -1;
  29711. /** @hidden */
  29712. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29713. /** @hidden */
  29714. this._comparisonFunction = 0;
  29715. /** @hidden */
  29716. this._sphericalPolynomial = null;
  29717. /** @hidden */
  29718. this._lodGenerationScale = 0;
  29719. /** @hidden */
  29720. this._lodGenerationOffset = 0;
  29721. /** @hidden */
  29722. this._isRGBD = false;
  29723. /** @hidden */
  29724. this._references = 1;
  29725. this._engine = engine;
  29726. this._dataSource = dataSource;
  29727. this._webGLTexture = engine._createTexture();
  29728. }
  29729. /**
  29730. * Gets the Engine the texture belongs to.
  29731. * @returns The babylon engine
  29732. */
  29733. InternalTexture.prototype.getEngine = function () {
  29734. return this._engine;
  29735. };
  29736. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29737. /**
  29738. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29739. */
  29740. get: function () {
  29741. return this._dataSource;
  29742. },
  29743. enumerable: true,
  29744. configurable: true
  29745. });
  29746. /**
  29747. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29748. */
  29749. InternalTexture.prototype.incrementReferences = function () {
  29750. this._references++;
  29751. };
  29752. /**
  29753. * Change the size of the texture (not the size of the content)
  29754. * @param width defines the new width
  29755. * @param height defines the new height
  29756. * @param depth defines the new depth (1 by default)
  29757. */
  29758. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29759. if (depth === void 0) { depth = 1; }
  29760. this.width = width;
  29761. this.height = height;
  29762. this.depth = depth;
  29763. this.baseWidth = width;
  29764. this.baseHeight = height;
  29765. this.baseDepth = depth;
  29766. this._size = width * height * depth;
  29767. };
  29768. /** @hidden */
  29769. InternalTexture.prototype._rebuild = function () {
  29770. var _this = this;
  29771. var proxy;
  29772. this.isReady = false;
  29773. this._cachedCoordinatesMode = null;
  29774. this._cachedWrapU = null;
  29775. this._cachedWrapV = null;
  29776. this._cachedAnisotropicFilteringLevel = null;
  29777. switch (this._dataSource) {
  29778. case InternalTexture.DATASOURCE_TEMP:
  29779. return;
  29780. case InternalTexture.DATASOURCE_URL:
  29781. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29782. _this.isReady = true;
  29783. }, null, this._buffer, undefined, this.format);
  29784. proxy._swapAndDie(this);
  29785. return;
  29786. case InternalTexture.DATASOURCE_RAW:
  29787. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29788. proxy._swapAndDie(this);
  29789. this.isReady = true;
  29790. return;
  29791. case InternalTexture.DATASOURCE_RAW3D:
  29792. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29793. proxy._swapAndDie(this);
  29794. this.isReady = true;
  29795. return;
  29796. case InternalTexture.DATASOURCE_DYNAMIC:
  29797. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29798. proxy._swapAndDie(this);
  29799. // The engine will make sure to update content so no need to flag it as isReady = true
  29800. return;
  29801. case InternalTexture.DATASOURCE_RENDERTARGET:
  29802. var options = new BABYLON.RenderTargetCreationOptions();
  29803. options.generateDepthBuffer = this._generateDepthBuffer;
  29804. options.generateMipMaps = this.generateMipMaps;
  29805. options.generateStencilBuffer = this._generateStencilBuffer;
  29806. options.samplingMode = this.samplingMode;
  29807. options.type = this.type;
  29808. if (this.isCube) {
  29809. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29810. }
  29811. else {
  29812. var size = {
  29813. width: this.width,
  29814. height: this.height
  29815. };
  29816. proxy = this._engine.createRenderTargetTexture(size, options);
  29817. }
  29818. proxy._swapAndDie(this);
  29819. this.isReady = true;
  29820. return;
  29821. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29822. var depthTextureOptions = {
  29823. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29824. comparisonFunction: this._comparisonFunction,
  29825. generateStencil: this._generateStencilBuffer,
  29826. isCube: this.isCube
  29827. };
  29828. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29829. proxy._swapAndDie(this);
  29830. this.isReady = true;
  29831. return;
  29832. case InternalTexture.DATASOURCE_CUBE:
  29833. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29834. _this.isReady = true;
  29835. }, null, this.format, this._extension);
  29836. proxy._swapAndDie(this);
  29837. return;
  29838. case InternalTexture.DATASOURCE_CUBERAW:
  29839. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29840. proxy._swapAndDie(this);
  29841. this.isReady = true;
  29842. return;
  29843. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29844. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29845. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29846. _this.isReady = true;
  29847. });
  29848. proxy._swapAndDie(this);
  29849. return;
  29850. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29851. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29852. if (proxy) {
  29853. proxy._swapAndDie(_this);
  29854. }
  29855. _this.isReady = true;
  29856. }, null, this.format, this._extension);
  29857. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29858. return;
  29859. }
  29860. };
  29861. InternalTexture.prototype._swapAndDie = function (target) {
  29862. target._webGLTexture = this._webGLTexture;
  29863. if (this._framebuffer) {
  29864. target._framebuffer = this._framebuffer;
  29865. }
  29866. if (this._depthStencilBuffer) {
  29867. target._depthStencilBuffer = this._depthStencilBuffer;
  29868. }
  29869. if (this._lodTextureHigh) {
  29870. if (target._lodTextureHigh) {
  29871. target._lodTextureHigh.dispose();
  29872. }
  29873. target._lodTextureHigh = this._lodTextureHigh;
  29874. }
  29875. if (this._lodTextureMid) {
  29876. if (target._lodTextureMid) {
  29877. target._lodTextureMid.dispose();
  29878. }
  29879. target._lodTextureMid = this._lodTextureMid;
  29880. }
  29881. if (this._lodTextureLow) {
  29882. if (target._lodTextureLow) {
  29883. target._lodTextureLow.dispose();
  29884. }
  29885. target._lodTextureLow = this._lodTextureLow;
  29886. }
  29887. var cache = this._engine.getLoadedTexturesCache();
  29888. var index = cache.indexOf(this);
  29889. if (index !== -1) {
  29890. cache.splice(index, 1);
  29891. }
  29892. };
  29893. /**
  29894. * Dispose the current allocated resources
  29895. */
  29896. InternalTexture.prototype.dispose = function () {
  29897. if (!this._webGLTexture) {
  29898. return;
  29899. }
  29900. this._references--;
  29901. if (this._references === 0) {
  29902. this._engine._releaseTexture(this);
  29903. this._webGLTexture = null;
  29904. this.previous = null;
  29905. this.next = null;
  29906. }
  29907. };
  29908. /**
  29909. * The source of the texture data is unknown
  29910. */
  29911. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29912. /**
  29913. * Texture data comes from an URL
  29914. */
  29915. InternalTexture.DATASOURCE_URL = 1;
  29916. /**
  29917. * Texture data is only used for temporary storage
  29918. */
  29919. InternalTexture.DATASOURCE_TEMP = 2;
  29920. /**
  29921. * Texture data comes from raw data (ArrayBuffer)
  29922. */
  29923. InternalTexture.DATASOURCE_RAW = 3;
  29924. /**
  29925. * Texture content is dynamic (video or dynamic texture)
  29926. */
  29927. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29928. /**
  29929. * Texture content is generated by rendering to it
  29930. */
  29931. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29932. /**
  29933. * Texture content is part of a multi render target process
  29934. */
  29935. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29936. /**
  29937. * Texture data comes from a cube data file
  29938. */
  29939. InternalTexture.DATASOURCE_CUBE = 7;
  29940. /**
  29941. * Texture data comes from a raw cube data
  29942. */
  29943. InternalTexture.DATASOURCE_CUBERAW = 8;
  29944. /**
  29945. * Texture data come from a prefiltered cube data file
  29946. */
  29947. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29948. /**
  29949. * Texture content is raw 3D data
  29950. */
  29951. InternalTexture.DATASOURCE_RAW3D = 10;
  29952. /**
  29953. * Texture content is a depth texture
  29954. */
  29955. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29956. /**
  29957. * Texture data comes from a raw cube data encoded with RGBD
  29958. */
  29959. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29960. return InternalTexture;
  29961. }());
  29962. BABYLON.InternalTexture = InternalTexture;
  29963. })(BABYLON || (BABYLON = {}));
  29964. //# sourceMappingURL=babylon.internalTexture.js.map
  29965. var BABYLON;
  29966. (function (BABYLON) {
  29967. var BaseTexture = /** @class */ (function () {
  29968. function BaseTexture(scene) {
  29969. this._hasAlpha = false;
  29970. this.getAlphaFromRGB = false;
  29971. this.level = 1;
  29972. this.coordinatesIndex = 0;
  29973. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29974. /**
  29975. * | Value | Type | Description |
  29976. * | ----- | ------------------ | ----------- |
  29977. * | 0 | CLAMP_ADDRESSMODE | |
  29978. * | 1 | WRAP_ADDRESSMODE | |
  29979. * | 2 | MIRROR_ADDRESSMODE | |
  29980. */
  29981. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29982. /**
  29983. * | Value | Type | Description |
  29984. * | ----- | ------------------ | ----------- |
  29985. * | 0 | CLAMP_ADDRESSMODE | |
  29986. * | 1 | WRAP_ADDRESSMODE | |
  29987. * | 2 | MIRROR_ADDRESSMODE | |
  29988. */
  29989. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29990. /**
  29991. * | Value | Type | Description |
  29992. * | ----- | ------------------ | ----------- |
  29993. * | 0 | CLAMP_ADDRESSMODE | |
  29994. * | 1 | WRAP_ADDRESSMODE | |
  29995. * | 2 | MIRROR_ADDRESSMODE | |
  29996. */
  29997. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29998. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29999. this.isCube = false;
  30000. this.is3D = false;
  30001. this.gammaSpace = true;
  30002. this.invertZ = false;
  30003. this.lodLevelInAlpha = false;
  30004. this.isRenderTarget = false;
  30005. this.animations = new Array();
  30006. /**
  30007. * An event triggered when the texture is disposed.
  30008. */
  30009. this.onDisposeObservable = new BABYLON.Observable();
  30010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30011. this._cachedSize = BABYLON.Size.Zero();
  30012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30013. if (this._scene) {
  30014. this._scene.textures.push(this);
  30015. }
  30016. this._uid = null;
  30017. }
  30018. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30019. get: function () {
  30020. return this._hasAlpha;
  30021. },
  30022. set: function (value) {
  30023. if (this._hasAlpha === value) {
  30024. return;
  30025. }
  30026. this._hasAlpha = value;
  30027. if (this._scene) {
  30028. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30029. }
  30030. },
  30031. enumerable: true,
  30032. configurable: true
  30033. });
  30034. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30035. get: function () {
  30036. return this._coordinatesMode;
  30037. },
  30038. /**
  30039. * How a texture is mapped.
  30040. *
  30041. * | Value | Type | Description |
  30042. * | ----- | ----------------------------------- | ----------- |
  30043. * | 0 | EXPLICIT_MODE | |
  30044. * | 1 | SPHERICAL_MODE | |
  30045. * | 2 | PLANAR_MODE | |
  30046. * | 3 | CUBIC_MODE | |
  30047. * | 4 | PROJECTION_MODE | |
  30048. * | 5 | SKYBOX_MODE | |
  30049. * | 6 | INVCUBIC_MODE | |
  30050. * | 7 | EQUIRECTANGULAR_MODE | |
  30051. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30052. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30053. */
  30054. set: function (value) {
  30055. if (this._coordinatesMode === value) {
  30056. return;
  30057. }
  30058. this._coordinatesMode = value;
  30059. if (this._scene) {
  30060. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30061. }
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30067. /**
  30068. * Gets whether or not the texture contains RGBD data.
  30069. */
  30070. get: function () {
  30071. return this._texture != null && this._texture._isRGBD;
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30077. get: function () {
  30078. if (this._texture)
  30079. return this._texture._lodGenerationOffset;
  30080. return 0.0;
  30081. },
  30082. set: function (value) {
  30083. if (this._texture)
  30084. this._texture._lodGenerationOffset = value;
  30085. },
  30086. enumerable: true,
  30087. configurable: true
  30088. });
  30089. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30090. get: function () {
  30091. if (this._texture)
  30092. return this._texture._lodGenerationScale;
  30093. return 0.0;
  30094. },
  30095. set: function (value) {
  30096. if (this._texture)
  30097. this._texture._lodGenerationScale = value;
  30098. },
  30099. enumerable: true,
  30100. configurable: true
  30101. });
  30102. Object.defineProperty(BaseTexture.prototype, "uid", {
  30103. get: function () {
  30104. if (!this._uid) {
  30105. this._uid = BABYLON.Tools.RandomId();
  30106. }
  30107. return this._uid;
  30108. },
  30109. enumerable: true,
  30110. configurable: true
  30111. });
  30112. BaseTexture.prototype.toString = function () {
  30113. return this.name;
  30114. };
  30115. BaseTexture.prototype.getClassName = function () {
  30116. return "BaseTexture";
  30117. };
  30118. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30119. set: function (callback) {
  30120. if (this._onDisposeObserver) {
  30121. this.onDisposeObservable.remove(this._onDisposeObserver);
  30122. }
  30123. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30124. },
  30125. enumerable: true,
  30126. configurable: true
  30127. });
  30128. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30129. get: function () {
  30130. return true;
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. BaseTexture.prototype.getScene = function () {
  30136. return this._scene;
  30137. };
  30138. BaseTexture.prototype.getTextureMatrix = function () {
  30139. return BABYLON.Matrix.IdentityReadOnly;
  30140. };
  30141. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30142. return BABYLON.Matrix.IdentityReadOnly;
  30143. };
  30144. BaseTexture.prototype.getInternalTexture = function () {
  30145. return this._texture;
  30146. };
  30147. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30148. return !this.isBlocking || this.isReady();
  30149. };
  30150. BaseTexture.prototype.isReady = function () {
  30151. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30152. this.delayLoad();
  30153. return false;
  30154. }
  30155. if (this._texture) {
  30156. return this._texture.isReady;
  30157. }
  30158. return false;
  30159. };
  30160. BaseTexture.prototype.getSize = function () {
  30161. if (this._texture) {
  30162. if (this._texture.width) {
  30163. this._cachedSize.width = this._texture.width;
  30164. this._cachedSize.height = this._texture.height;
  30165. return this._cachedSize;
  30166. }
  30167. if (this._texture._size) {
  30168. this._cachedSize.width = this._texture._size;
  30169. this._cachedSize.height = this._texture._size;
  30170. return this._cachedSize;
  30171. }
  30172. }
  30173. return this._cachedSize;
  30174. };
  30175. BaseTexture.prototype.getBaseSize = function () {
  30176. if (!this.isReady() || !this._texture)
  30177. return BABYLON.Size.Zero();
  30178. if (this._texture._size) {
  30179. return new BABYLON.Size(this._texture._size, this._texture._size);
  30180. }
  30181. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30182. };
  30183. BaseTexture.prototype.scale = function (ratio) {
  30184. };
  30185. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30186. get: function () {
  30187. return false;
  30188. },
  30189. enumerable: true,
  30190. configurable: true
  30191. });
  30192. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30193. if (!this._scene) {
  30194. return null;
  30195. }
  30196. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30197. for (var index = 0; index < texturesCache.length; index++) {
  30198. var texturesCacheEntry = texturesCache[index];
  30199. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30200. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30201. texturesCacheEntry.incrementReferences();
  30202. return texturesCacheEntry;
  30203. }
  30204. }
  30205. }
  30206. return null;
  30207. };
  30208. BaseTexture.prototype._rebuild = function () {
  30209. };
  30210. BaseTexture.prototype.delayLoad = function () {
  30211. };
  30212. BaseTexture.prototype.clone = function () {
  30213. return null;
  30214. };
  30215. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30216. get: function () {
  30217. if (!this._texture) {
  30218. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30219. }
  30220. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30226. get: function () {
  30227. if (!this._texture) {
  30228. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30229. }
  30230. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. /**
  30236. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30237. * This will returns an RGBA array buffer containing either in values (0-255) or
  30238. * float values (0-1) depending of the underlying buffer type.
  30239. * @param faceIndex The face of the texture to read (in case of cube texture)
  30240. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30241. * @returns The Array buffer containing the pixels data.
  30242. */
  30243. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30244. if (faceIndex === void 0) { faceIndex = 0; }
  30245. if (level === void 0) { level = 0; }
  30246. if (!this._texture) {
  30247. return null;
  30248. }
  30249. var size = this.getSize();
  30250. var width = size.width;
  30251. var height = size.height;
  30252. var scene = this.getScene();
  30253. if (!scene) {
  30254. return null;
  30255. }
  30256. var engine = scene.getEngine();
  30257. if (level != 0) {
  30258. width = width / Math.pow(2, level);
  30259. height = height / Math.pow(2, level);
  30260. width = Math.round(width);
  30261. height = Math.round(height);
  30262. }
  30263. if (this._texture.isCube) {
  30264. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30265. }
  30266. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30267. };
  30268. BaseTexture.prototype.releaseInternalTexture = function () {
  30269. if (this._texture) {
  30270. this._texture.dispose();
  30271. this._texture = null;
  30272. }
  30273. };
  30274. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30275. get: function () {
  30276. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30277. return null;
  30278. }
  30279. if (!this._texture._sphericalPolynomial) {
  30280. this._texture._sphericalPolynomial =
  30281. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30282. }
  30283. return this._texture._sphericalPolynomial;
  30284. },
  30285. set: function (value) {
  30286. if (this._texture) {
  30287. this._texture._sphericalPolynomial = value;
  30288. }
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30294. get: function () {
  30295. if (this._texture) {
  30296. return this._texture._lodTextureHigh;
  30297. }
  30298. return null;
  30299. },
  30300. enumerable: true,
  30301. configurable: true
  30302. });
  30303. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30304. get: function () {
  30305. if (this._texture) {
  30306. return this._texture._lodTextureMid;
  30307. }
  30308. return null;
  30309. },
  30310. enumerable: true,
  30311. configurable: true
  30312. });
  30313. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30314. get: function () {
  30315. if (this._texture) {
  30316. return this._texture._lodTextureLow;
  30317. }
  30318. return null;
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. BaseTexture.prototype.dispose = function () {
  30324. if (!this._scene) {
  30325. return;
  30326. }
  30327. // Animations
  30328. this._scene.stopAnimation(this);
  30329. // Remove from scene
  30330. this._scene._removePendingData(this);
  30331. var index = this._scene.textures.indexOf(this);
  30332. if (index >= 0) {
  30333. this._scene.textures.splice(index, 1);
  30334. }
  30335. if (this._texture === undefined) {
  30336. return;
  30337. }
  30338. // Release
  30339. this.releaseInternalTexture();
  30340. // Callback
  30341. this.onDisposeObservable.notifyObservers(this);
  30342. this.onDisposeObservable.clear();
  30343. };
  30344. BaseTexture.prototype.serialize = function () {
  30345. if (!this.name) {
  30346. return null;
  30347. }
  30348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30349. // Animations
  30350. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30351. return serializationObject;
  30352. };
  30353. BaseTexture.WhenAllReady = function (textures, callback) {
  30354. var numRemaining = textures.length;
  30355. if (numRemaining === 0) {
  30356. callback();
  30357. return;
  30358. }
  30359. var _loop_1 = function () {
  30360. texture = textures[i];
  30361. if (texture.isReady()) {
  30362. if (--numRemaining === 0) {
  30363. callback();
  30364. }
  30365. }
  30366. else {
  30367. onLoadObservable = texture.onLoadObservable;
  30368. var onLoadCallback_1 = function () {
  30369. onLoadObservable.removeCallback(onLoadCallback_1);
  30370. if (--numRemaining === 0) {
  30371. callback();
  30372. }
  30373. };
  30374. onLoadObservable.add(onLoadCallback_1);
  30375. }
  30376. };
  30377. var texture, onLoadObservable;
  30378. for (var i = 0; i < textures.length; i++) {
  30379. _loop_1();
  30380. }
  30381. };
  30382. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30383. __decorate([
  30384. BABYLON.serialize()
  30385. ], BaseTexture.prototype, "name", void 0);
  30386. __decorate([
  30387. BABYLON.serialize("hasAlpha")
  30388. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30389. __decorate([
  30390. BABYLON.serialize()
  30391. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30392. __decorate([
  30393. BABYLON.serialize()
  30394. ], BaseTexture.prototype, "level", void 0);
  30395. __decorate([
  30396. BABYLON.serialize()
  30397. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30398. __decorate([
  30399. BABYLON.serialize("coordinatesMode")
  30400. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30401. __decorate([
  30402. BABYLON.serialize()
  30403. ], BaseTexture.prototype, "wrapU", void 0);
  30404. __decorate([
  30405. BABYLON.serialize()
  30406. ], BaseTexture.prototype, "wrapV", void 0);
  30407. __decorate([
  30408. BABYLON.serialize()
  30409. ], BaseTexture.prototype, "wrapR", void 0);
  30410. __decorate([
  30411. BABYLON.serialize()
  30412. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30413. __decorate([
  30414. BABYLON.serialize()
  30415. ], BaseTexture.prototype, "isCube", void 0);
  30416. __decorate([
  30417. BABYLON.serialize()
  30418. ], BaseTexture.prototype, "is3D", void 0);
  30419. __decorate([
  30420. BABYLON.serialize()
  30421. ], BaseTexture.prototype, "gammaSpace", void 0);
  30422. __decorate([
  30423. BABYLON.serialize()
  30424. ], BaseTexture.prototype, "invertZ", void 0);
  30425. __decorate([
  30426. BABYLON.serialize()
  30427. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30428. __decorate([
  30429. BABYLON.serialize()
  30430. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30431. __decorate([
  30432. BABYLON.serialize()
  30433. ], BaseTexture.prototype, "lodGenerationScale", null);
  30434. __decorate([
  30435. BABYLON.serialize()
  30436. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30437. return BaseTexture;
  30438. }());
  30439. BABYLON.BaseTexture = BaseTexture;
  30440. })(BABYLON || (BABYLON = {}));
  30441. //# sourceMappingURL=babylon.baseTexture.js.map
  30442. var BABYLON;
  30443. (function (BABYLON) {
  30444. var Texture = /** @class */ (function (_super) {
  30445. __extends(Texture, _super);
  30446. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30447. if (noMipmap === void 0) { noMipmap = false; }
  30448. if (invertY === void 0) { invertY = true; }
  30449. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30450. if (onLoad === void 0) { onLoad = null; }
  30451. if (onError === void 0) { onError = null; }
  30452. if (buffer === void 0) { buffer = null; }
  30453. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30454. var _this = _super.call(this, scene) || this;
  30455. _this.uOffset = 0;
  30456. _this.vOffset = 0;
  30457. _this.uScale = 1.0;
  30458. _this.vScale = 1.0;
  30459. _this.uAng = 0;
  30460. _this.vAng = 0;
  30461. _this.wAng = 0;
  30462. /**
  30463. * Defines the center of rotation (U)
  30464. */
  30465. _this.uRotationCenter = 0.5;
  30466. /**
  30467. * Defines the center of rotation (V)
  30468. */
  30469. _this.vRotationCenter = 0.5;
  30470. /**
  30471. * Defines the center of rotation (W)
  30472. */
  30473. _this.wRotationCenter = 0.5;
  30474. _this._isBlocking = true;
  30475. _this.name = url || "";
  30476. _this.url = url;
  30477. _this._noMipmap = noMipmap;
  30478. _this._invertY = invertY;
  30479. _this._samplingMode = samplingMode;
  30480. _this._buffer = buffer;
  30481. _this._deleteBuffer = deleteBuffer;
  30482. if (format) {
  30483. _this._format = format;
  30484. }
  30485. scene = _this.getScene();
  30486. if (!scene) {
  30487. return _this;
  30488. }
  30489. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30490. var load = function () {
  30491. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30492. _this.onLoadObservable.notifyObservers(_this);
  30493. }
  30494. if (onLoad) {
  30495. onLoad();
  30496. }
  30497. if (!_this.isBlocking && scene) {
  30498. scene.resetCachedMaterial();
  30499. }
  30500. };
  30501. if (!_this.url) {
  30502. _this._delayedOnLoad = load;
  30503. _this._delayedOnError = onError;
  30504. return _this;
  30505. }
  30506. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30507. if (!_this._texture) {
  30508. if (!scene.useDelayedTextureLoading) {
  30509. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30510. if (deleteBuffer) {
  30511. delete _this._buffer;
  30512. }
  30513. }
  30514. else {
  30515. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30516. _this._delayedOnLoad = load;
  30517. _this._delayedOnError = onError;
  30518. }
  30519. }
  30520. else {
  30521. if (_this._texture.isReady) {
  30522. BABYLON.Tools.SetImmediate(function () { return load(); });
  30523. }
  30524. else {
  30525. _this._texture.onLoadedObservable.add(load);
  30526. }
  30527. }
  30528. return _this;
  30529. }
  30530. Object.defineProperty(Texture.prototype, "noMipmap", {
  30531. get: function () {
  30532. return this._noMipmap;
  30533. },
  30534. enumerable: true,
  30535. configurable: true
  30536. });
  30537. Object.defineProperty(Texture.prototype, "isBlocking", {
  30538. get: function () {
  30539. return this._isBlocking;
  30540. },
  30541. set: function (value) {
  30542. this._isBlocking = value;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(Texture.prototype, "samplingMode", {
  30548. get: function () {
  30549. return this._samplingMode;
  30550. },
  30551. enumerable: true,
  30552. configurable: true
  30553. });
  30554. /**
  30555. * Update the url (and optional buffer) of this texture if url was null during construction.
  30556. * @param url the url of the texture
  30557. * @param buffer the buffer of the texture (defaults to null)
  30558. */
  30559. Texture.prototype.updateURL = function (url, buffer) {
  30560. if (buffer === void 0) { buffer = null; }
  30561. if (this.url) {
  30562. throw new Error("URL is already set");
  30563. }
  30564. this.url = url;
  30565. this._buffer = buffer;
  30566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30567. this.delayLoad();
  30568. };
  30569. Texture.prototype.delayLoad = function () {
  30570. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30571. return;
  30572. }
  30573. var scene = this.getScene();
  30574. if (!scene) {
  30575. return;
  30576. }
  30577. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30578. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30579. if (!this._texture) {
  30580. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30581. if (this._deleteBuffer) {
  30582. delete this._buffer;
  30583. }
  30584. }
  30585. else {
  30586. if (this._delayedOnLoad) {
  30587. if (this._texture.isReady) {
  30588. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30589. }
  30590. else {
  30591. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30592. }
  30593. }
  30594. }
  30595. this._delayedOnLoad = null;
  30596. this._delayedOnError = null;
  30597. };
  30598. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30599. if (!this._texture) {
  30600. return;
  30601. }
  30602. var scene = this.getScene();
  30603. if (!scene) {
  30604. return;
  30605. }
  30606. this._samplingMode = samplingMode;
  30607. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30608. };
  30609. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30610. x *= this.uScale;
  30611. y *= this.vScale;
  30612. x -= this.uRotationCenter * this.uScale;
  30613. y -= this.vRotationCenter * this.vScale;
  30614. z -= this.wRotationCenter;
  30615. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30616. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30617. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30618. t.z += this.wRotationCenter;
  30619. };
  30620. Texture.prototype.getTextureMatrix = function () {
  30621. var _this = this;
  30622. if (this.uOffset === this._cachedUOffset &&
  30623. this.vOffset === this._cachedVOffset &&
  30624. this.uScale === this._cachedUScale &&
  30625. this.vScale === this._cachedVScale &&
  30626. this.uAng === this._cachedUAng &&
  30627. this.vAng === this._cachedVAng &&
  30628. this.wAng === this._cachedWAng) {
  30629. return this._cachedTextureMatrix;
  30630. }
  30631. this._cachedUOffset = this.uOffset;
  30632. this._cachedVOffset = this.vOffset;
  30633. this._cachedUScale = this.uScale;
  30634. this._cachedVScale = this.vScale;
  30635. this._cachedUAng = this.uAng;
  30636. this._cachedVAng = this.vAng;
  30637. this._cachedWAng = this.wAng;
  30638. if (!this._cachedTextureMatrix) {
  30639. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30640. this._rowGenerationMatrix = new BABYLON.Matrix();
  30641. this._t0 = BABYLON.Vector3.Zero();
  30642. this._t1 = BABYLON.Vector3.Zero();
  30643. this._t2 = BABYLON.Vector3.Zero();
  30644. }
  30645. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30646. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30647. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30648. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30649. this._t1.subtractInPlace(this._t0);
  30650. this._t2.subtractInPlace(this._t0);
  30651. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30652. this._cachedTextureMatrix.m[0] = this._t1.x;
  30653. this._cachedTextureMatrix.m[1] = this._t1.y;
  30654. this._cachedTextureMatrix.m[2] = this._t1.z;
  30655. this._cachedTextureMatrix.m[4] = this._t2.x;
  30656. this._cachedTextureMatrix.m[5] = this._t2.y;
  30657. this._cachedTextureMatrix.m[6] = this._t2.z;
  30658. this._cachedTextureMatrix.m[8] = this._t0.x;
  30659. this._cachedTextureMatrix.m[9] = this._t0.y;
  30660. this._cachedTextureMatrix.m[10] = this._t0.z;
  30661. var scene = this.getScene();
  30662. if (!scene) {
  30663. return this._cachedTextureMatrix;
  30664. }
  30665. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30666. return mat.hasTexture(_this);
  30667. });
  30668. return this._cachedTextureMatrix;
  30669. };
  30670. Texture.prototype.getReflectionTextureMatrix = function () {
  30671. var _this = this;
  30672. var scene = this.getScene();
  30673. if (!scene) {
  30674. return this._cachedTextureMatrix;
  30675. }
  30676. if (this.uOffset === this._cachedUOffset &&
  30677. this.vOffset === this._cachedVOffset &&
  30678. this.uScale === this._cachedUScale &&
  30679. this.vScale === this._cachedVScale &&
  30680. this.coordinatesMode === this._cachedCoordinatesMode) {
  30681. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30682. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30683. return this._cachedTextureMatrix;
  30684. }
  30685. }
  30686. else {
  30687. return this._cachedTextureMatrix;
  30688. }
  30689. }
  30690. if (!this._cachedTextureMatrix) {
  30691. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30692. }
  30693. if (!this._projectionModeMatrix) {
  30694. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30695. }
  30696. this._cachedUOffset = this.uOffset;
  30697. this._cachedVOffset = this.vOffset;
  30698. this._cachedUScale = this.uScale;
  30699. this._cachedVScale = this.vScale;
  30700. this._cachedCoordinatesMode = this.coordinatesMode;
  30701. switch (this.coordinatesMode) {
  30702. case Texture.PLANAR_MODE:
  30703. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30704. this._cachedTextureMatrix[0] = this.uScale;
  30705. this._cachedTextureMatrix[5] = this.vScale;
  30706. this._cachedTextureMatrix[12] = this.uOffset;
  30707. this._cachedTextureMatrix[13] = this.vOffset;
  30708. break;
  30709. case Texture.PROJECTION_MODE:
  30710. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30711. this._projectionModeMatrix.m[0] = 0.5;
  30712. this._projectionModeMatrix.m[5] = -0.5;
  30713. this._projectionModeMatrix.m[10] = 0.0;
  30714. this._projectionModeMatrix.m[12] = 0.5;
  30715. this._projectionModeMatrix.m[13] = 0.5;
  30716. this._projectionModeMatrix.m[14] = 1.0;
  30717. this._projectionModeMatrix.m[15] = 1.0;
  30718. var projectionMatrix = scene.getProjectionMatrix();
  30719. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30720. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30721. break;
  30722. default:
  30723. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30724. break;
  30725. }
  30726. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30727. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30728. });
  30729. return this._cachedTextureMatrix;
  30730. };
  30731. Texture.prototype.clone = function () {
  30732. var _this = this;
  30733. return BABYLON.SerializationHelper.Clone(function () {
  30734. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30735. }, this);
  30736. };
  30737. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30738. get: function () {
  30739. if (!this._onLoadObservable) {
  30740. this._onLoadObservable = new BABYLON.Observable();
  30741. }
  30742. return this._onLoadObservable;
  30743. },
  30744. enumerable: true,
  30745. configurable: true
  30746. });
  30747. Texture.prototype.serialize = function () {
  30748. var serializationObject = _super.prototype.serialize.call(this);
  30749. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30750. serializationObject.base64String = this._buffer;
  30751. serializationObject.name = serializationObject.name.replace("data:", "");
  30752. }
  30753. serializationObject.invertY = this._invertY;
  30754. serializationObject.samplingMode = this.samplingMode;
  30755. return serializationObject;
  30756. };
  30757. Texture.prototype.getClassName = function () {
  30758. return "Texture";
  30759. };
  30760. Texture.prototype.dispose = function () {
  30761. _super.prototype.dispose.call(this);
  30762. if (this._onLoadObservable) {
  30763. this._onLoadObservable.clear();
  30764. this._onLoadObservable = null;
  30765. }
  30766. this._delayedOnLoad = null;
  30767. this._delayedOnError = null;
  30768. };
  30769. // Statics
  30770. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30771. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30772. if (onLoad === void 0) { onLoad = null; }
  30773. if (onError === void 0) { onError = null; }
  30774. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30775. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30776. };
  30777. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30778. if (parsedTexture.customType) {
  30779. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30780. // Update Sampling Mode
  30781. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30782. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30783. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30784. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30785. }
  30786. }
  30787. return parsedCustomTexture;
  30788. }
  30789. if (parsedTexture.isCube) {
  30790. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30791. }
  30792. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30793. return null;
  30794. }
  30795. var texture = BABYLON.SerializationHelper.Parse(function () {
  30796. var generateMipMaps = true;
  30797. if (parsedTexture.noMipmap) {
  30798. generateMipMaps = false;
  30799. }
  30800. if (parsedTexture.mirrorPlane) {
  30801. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30802. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30803. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30804. return mirrorTexture;
  30805. }
  30806. else if (parsedTexture.isRenderTarget) {
  30807. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30808. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30809. return renderTargetTexture;
  30810. }
  30811. else {
  30812. var texture;
  30813. if (parsedTexture.base64String) {
  30814. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30815. }
  30816. else {
  30817. var url = rootUrl + parsedTexture.name;
  30818. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30819. url = parsedTexture.url;
  30820. }
  30821. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30822. }
  30823. return texture;
  30824. }
  30825. }, parsedTexture, scene);
  30826. // Update Sampling Mode
  30827. if (parsedTexture.samplingMode) {
  30828. var sampling = parsedTexture.samplingMode;
  30829. if (texture._samplingMode !== sampling) {
  30830. texture.updateSamplingMode(sampling);
  30831. }
  30832. }
  30833. // Animations
  30834. if (parsedTexture.animations) {
  30835. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30836. var parsedAnimation = parsedTexture.animations[animationIndex];
  30837. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30838. }
  30839. }
  30840. return texture;
  30841. };
  30842. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30843. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30844. if (noMipmap === void 0) { noMipmap = false; }
  30845. if (invertY === void 0) { invertY = true; }
  30846. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30847. if (onLoad === void 0) { onLoad = null; }
  30848. if (onError === void 0) { onError = null; }
  30849. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30850. if (name.substr(0, 5) !== "data:") {
  30851. name = "data:" + name;
  30852. }
  30853. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30854. };
  30855. // Constants
  30856. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30857. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30858. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30859. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30860. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30861. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30862. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30863. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30864. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30865. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30866. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30867. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30868. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30869. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30870. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30871. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30872. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30873. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30874. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30875. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30876. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30877. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30878. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30879. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30880. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30881. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30882. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30883. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30884. /**
  30885. * 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
  30886. */
  30887. Texture.UseSerializedUrlIfAny = false;
  30888. __decorate([
  30889. BABYLON.serialize()
  30890. ], Texture.prototype, "url", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], Texture.prototype, "uOffset", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], Texture.prototype, "vOffset", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], Texture.prototype, "uScale", void 0);
  30900. __decorate([
  30901. BABYLON.serialize()
  30902. ], Texture.prototype, "vScale", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "uAng", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "vAng", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], Texture.prototype, "wAng", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], Texture.prototype, "uRotationCenter", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], Texture.prototype, "vRotationCenter", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], Texture.prototype, "wRotationCenter", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], Texture.prototype, "isBlocking", null);
  30924. return Texture;
  30925. }(BABYLON.BaseTexture));
  30926. BABYLON.Texture = Texture;
  30927. })(BABYLON || (BABYLON = {}));
  30928. //# sourceMappingURL=babylon.texture.js.map
  30929. var BABYLON;
  30930. (function (BABYLON) {
  30931. /**
  30932. * @hidden
  30933. **/
  30934. var _InstancesBatch = /** @class */ (function () {
  30935. function _InstancesBatch() {
  30936. this.mustReturn = false;
  30937. this.visibleInstances = new Array();
  30938. this.renderSelf = new Array();
  30939. }
  30940. return _InstancesBatch;
  30941. }());
  30942. BABYLON._InstancesBatch = _InstancesBatch;
  30943. var Mesh = /** @class */ (function (_super) {
  30944. __extends(Mesh, _super);
  30945. /**
  30946. * @constructor
  30947. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30948. * @param {Scene} scene The scene to add this mesh to.
  30949. * @param {Node} parent The parent of this mesh, if it has one
  30950. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30951. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30952. * When false, achieved by calling a clone(), also passing False.
  30953. * This will make creation of children, recursive.
  30954. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30955. */
  30956. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30957. if (scene === void 0) { scene = null; }
  30958. if (parent === void 0) { parent = null; }
  30959. if (source === void 0) { source = null; }
  30960. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30961. var _this = _super.call(this, name, scene) || this;
  30962. // Events
  30963. /**
  30964. * An event triggered before rendering the mesh
  30965. */
  30966. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30967. /**
  30968. * An event triggered after rendering the mesh
  30969. */
  30970. _this.onAfterRenderObservable = new BABYLON.Observable();
  30971. /**
  30972. * An event triggered before drawing the mesh
  30973. */
  30974. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30975. // Members
  30976. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30977. _this.instances = new Array();
  30978. _this._LODLevels = new Array();
  30979. _this._visibleInstances = {};
  30980. _this._renderIdForInstances = new Array();
  30981. _this._batchCache = new _InstancesBatch();
  30982. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30983. // Use by builder only to know what orientation were the mesh build in.
  30984. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30985. _this.overrideMaterialSideOrientation = null;
  30986. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30987. // Will be used to save a source mesh reference, If any
  30988. _this._source = null;
  30989. scene = _this.getScene();
  30990. if (source) {
  30991. // Geometry
  30992. if (source._geometry) {
  30993. source._geometry.applyToMesh(_this);
  30994. }
  30995. // Deep copy
  30996. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30997. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30998. // Source mesh
  30999. _this._source = source;
  31000. // Metadata
  31001. if (source.metadata && source.metadata.clone) {
  31002. _this.metadata = source.metadata.clone();
  31003. }
  31004. else {
  31005. _this.metadata = source.metadata;
  31006. }
  31007. // Tags
  31008. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31009. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31010. }
  31011. // Parent
  31012. _this.parent = source.parent;
  31013. // Pivot
  31014. _this.setPivotMatrix(source.getPivotMatrix());
  31015. _this.id = name + "." + source.id;
  31016. // Material
  31017. _this.material = source.material;
  31018. var index;
  31019. if (!doNotCloneChildren) {
  31020. // Children
  31021. var directDescendants = source.getDescendants(true);
  31022. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31023. var child = directDescendants[index_1];
  31024. if (child.clone) {
  31025. child.clone(name + "." + child.name, _this);
  31026. }
  31027. }
  31028. }
  31029. // Physics clone
  31030. var physicsEngine = _this.getScene().getPhysicsEngine();
  31031. if (clonePhysicsImpostor && physicsEngine) {
  31032. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31033. if (impostor) {
  31034. _this.physicsImpostor = impostor.clone(_this);
  31035. }
  31036. }
  31037. // Particles
  31038. for (index = 0; index < scene.particleSystems.length; index++) {
  31039. var system = scene.particleSystems[index];
  31040. if (system.emitter === source) {
  31041. system.clone(system.name, _this);
  31042. }
  31043. }
  31044. _this.refreshBoundingInfo();
  31045. _this.computeWorldMatrix(true);
  31046. }
  31047. // Parent
  31048. if (parent !== null) {
  31049. _this.parent = parent;
  31050. }
  31051. return _this;
  31052. }
  31053. Object.defineProperty(Mesh, "FRONTSIDE", {
  31054. /**
  31055. * Mesh side orientation : usually the external or front surface
  31056. */
  31057. get: function () {
  31058. return Mesh._FRONTSIDE;
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(Mesh, "BACKSIDE", {
  31064. /**
  31065. * Mesh side orientation : usually the internal or back surface
  31066. */
  31067. get: function () {
  31068. return Mesh._BACKSIDE;
  31069. },
  31070. enumerable: true,
  31071. configurable: true
  31072. });
  31073. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31074. /**
  31075. * Mesh side orientation : both internal and external or front and back surfaces
  31076. */
  31077. get: function () {
  31078. return Mesh._DOUBLESIDE;
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31084. /**
  31085. * Mesh side orientation : by default, `FRONTSIDE`
  31086. */
  31087. get: function () {
  31088. return Mesh._DEFAULTSIDE;
  31089. },
  31090. enumerable: true,
  31091. configurable: true
  31092. });
  31093. Object.defineProperty(Mesh, "NO_CAP", {
  31094. /**
  31095. * Mesh cap setting : no cap
  31096. */
  31097. get: function () {
  31098. return Mesh._NO_CAP;
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. Object.defineProperty(Mesh, "CAP_START", {
  31104. /**
  31105. * Mesh cap setting : one cap at the beginning of the mesh
  31106. */
  31107. get: function () {
  31108. return Mesh._CAP_START;
  31109. },
  31110. enumerable: true,
  31111. configurable: true
  31112. });
  31113. Object.defineProperty(Mesh, "CAP_END", {
  31114. /**
  31115. * Mesh cap setting : one cap at the end of the mesh
  31116. */
  31117. get: function () {
  31118. return Mesh._CAP_END;
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Mesh, "CAP_ALL", {
  31124. /**
  31125. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31126. */
  31127. get: function () {
  31128. return Mesh._CAP_ALL;
  31129. },
  31130. enumerable: true,
  31131. configurable: true
  31132. });
  31133. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31134. set: function (callback) {
  31135. if (this._onBeforeDrawObserver) {
  31136. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31137. }
  31138. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31139. },
  31140. enumerable: true,
  31141. configurable: true
  31142. });
  31143. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31144. get: function () {
  31145. return this._morphTargetManager;
  31146. },
  31147. set: function (value) {
  31148. if (this._morphTargetManager === value) {
  31149. return;
  31150. }
  31151. this._morphTargetManager = value;
  31152. this._syncGeometryWithMorphTargetManager();
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. Object.defineProperty(Mesh.prototype, "source", {
  31158. get: function () {
  31159. return this._source;
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31165. get: function () {
  31166. return this._unIndexed;
  31167. },
  31168. set: function (value) {
  31169. if (this._unIndexed !== value) {
  31170. this._unIndexed = value;
  31171. this._markSubMeshesAsAttributesDirty();
  31172. }
  31173. },
  31174. enumerable: true,
  31175. configurable: true
  31176. });
  31177. // Methods
  31178. /**
  31179. * Returns the string "Mesh".
  31180. */
  31181. Mesh.prototype.getClassName = function () {
  31182. return "Mesh";
  31183. };
  31184. /**
  31185. * Returns a string.
  31186. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31187. */
  31188. Mesh.prototype.toString = function (fullDetails) {
  31189. var ret = _super.prototype.toString.call(this, fullDetails);
  31190. ret += ", n vertices: " + this.getTotalVertices();
  31191. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31192. if (this.animations) {
  31193. for (var i = 0; i < this.animations.length; i++) {
  31194. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31195. }
  31196. }
  31197. if (fullDetails) {
  31198. if (this._geometry) {
  31199. var ib = this.getIndices();
  31200. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31201. if (vb && ib) {
  31202. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31203. }
  31204. }
  31205. else {
  31206. ret += ", flat shading: UNKNOWN";
  31207. }
  31208. }
  31209. return ret;
  31210. };
  31211. Mesh.prototype._unBindEffect = function () {
  31212. _super.prototype._unBindEffect.call(this);
  31213. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31214. var instance = _a[_i];
  31215. instance._unBindEffect();
  31216. }
  31217. };
  31218. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31219. /**
  31220. * True if the mesh has some Levels Of Details (LOD).
  31221. * Returns a boolean.
  31222. */
  31223. get: function () {
  31224. return this._LODLevels.length > 0;
  31225. },
  31226. enumerable: true,
  31227. configurable: true
  31228. });
  31229. /**
  31230. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31231. * @returns an array of {BABYLON.MeshLODLevel}
  31232. */
  31233. Mesh.prototype.getLODLevels = function () {
  31234. return this._LODLevels;
  31235. };
  31236. Mesh.prototype._sortLODLevels = function () {
  31237. this._LODLevels.sort(function (a, b) {
  31238. if (a.distance < b.distance) {
  31239. return 1;
  31240. }
  31241. if (a.distance > b.distance) {
  31242. return -1;
  31243. }
  31244. return 0;
  31245. });
  31246. };
  31247. /**
  31248. * Add a mesh as LOD level triggered at the given distance.
  31249. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31250. * @param distance The distance from the center of the object to show this level
  31251. * @param mesh The mesh to be added as LOD level (can be null)
  31252. * @return This mesh (for chaining)
  31253. */
  31254. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31255. if (mesh && mesh._masterMesh) {
  31256. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31257. return this;
  31258. }
  31259. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31260. this._LODLevels.push(level);
  31261. if (mesh) {
  31262. mesh._masterMesh = this;
  31263. }
  31264. this._sortLODLevels();
  31265. return this;
  31266. };
  31267. /**
  31268. * Returns the LOD level mesh at the passed distance or null if not found.
  31269. * It is related to the method `addLODLevel(distance, mesh)`.
  31270. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31271. * Returns an object Mesh or `null`.
  31272. */
  31273. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31274. for (var index = 0; index < this._LODLevels.length; index++) {
  31275. var level = this._LODLevels[index];
  31276. if (level.distance === distance) {
  31277. return level.mesh;
  31278. }
  31279. }
  31280. return null;
  31281. };
  31282. /**
  31283. * Remove a mesh from the LOD array
  31284. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31285. * @param {Mesh} mesh The mesh to be removed.
  31286. * @return {Mesh} This mesh (for chaining)
  31287. */
  31288. Mesh.prototype.removeLODLevel = function (mesh) {
  31289. for (var index = 0; index < this._LODLevels.length; index++) {
  31290. if (this._LODLevels[index].mesh === mesh) {
  31291. this._LODLevels.splice(index, 1);
  31292. if (mesh) {
  31293. mesh._masterMesh = null;
  31294. }
  31295. }
  31296. }
  31297. this._sortLODLevels();
  31298. return this;
  31299. };
  31300. /**
  31301. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31302. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31303. */
  31304. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31305. if (!this._LODLevels || this._LODLevels.length === 0) {
  31306. return this;
  31307. }
  31308. var bSphere;
  31309. if (boundingSphere) {
  31310. bSphere = boundingSphere;
  31311. }
  31312. else {
  31313. var boundingInfo = this.getBoundingInfo();
  31314. bSphere = boundingInfo.boundingSphere;
  31315. }
  31316. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31317. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31318. if (this.onLODLevelSelection) {
  31319. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31320. }
  31321. return this;
  31322. }
  31323. for (var index = 0; index < this._LODLevels.length; index++) {
  31324. var level = this._LODLevels[index];
  31325. if (level.distance < distanceToCamera) {
  31326. if (level.mesh) {
  31327. level.mesh._preActivate();
  31328. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31329. }
  31330. if (this.onLODLevelSelection) {
  31331. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31332. }
  31333. return level.mesh;
  31334. }
  31335. }
  31336. if (this.onLODLevelSelection) {
  31337. this.onLODLevelSelection(distanceToCamera, this, this);
  31338. }
  31339. return this;
  31340. };
  31341. Object.defineProperty(Mesh.prototype, "geometry", {
  31342. /**
  31343. * Returns the mesh internal Geometry object.
  31344. */
  31345. get: function () {
  31346. return this._geometry;
  31347. },
  31348. enumerable: true,
  31349. configurable: true
  31350. });
  31351. /**
  31352. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31353. */
  31354. Mesh.prototype.getTotalVertices = function () {
  31355. if (this._geometry === null || this._geometry === undefined) {
  31356. return 0;
  31357. }
  31358. return this._geometry.getTotalVertices();
  31359. };
  31360. /**
  31361. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31362. * 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.
  31363. * You can force the copy with forceCopy === true
  31364. * Returns null if the mesh has no geometry or no vertex buffer.
  31365. * Possible `kind` values :
  31366. * - BABYLON.VertexBuffer.PositionKind
  31367. * - BABYLON.VertexBuffer.UVKind
  31368. * - BABYLON.VertexBuffer.UV2Kind
  31369. * - BABYLON.VertexBuffer.UV3Kind
  31370. * - BABYLON.VertexBuffer.UV4Kind
  31371. * - BABYLON.VertexBuffer.UV5Kind
  31372. * - BABYLON.VertexBuffer.UV6Kind
  31373. * - BABYLON.VertexBuffer.ColorKind
  31374. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31375. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31376. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31377. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31378. */
  31379. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31380. if (!this._geometry) {
  31381. return null;
  31382. }
  31383. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31384. };
  31385. /**
  31386. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31387. * Returns `null` if the mesh has no geometry.
  31388. * Possible `kind` values :
  31389. * - BABYLON.VertexBuffer.PositionKind
  31390. * - BABYLON.VertexBuffer.UVKind
  31391. * - BABYLON.VertexBuffer.UV2Kind
  31392. * - BABYLON.VertexBuffer.UV3Kind
  31393. * - BABYLON.VertexBuffer.UV4Kind
  31394. * - BABYLON.VertexBuffer.UV5Kind
  31395. * - BABYLON.VertexBuffer.UV6Kind
  31396. * - BABYLON.VertexBuffer.ColorKind
  31397. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31398. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31399. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31400. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31401. */
  31402. Mesh.prototype.getVertexBuffer = function (kind) {
  31403. if (!this._geometry) {
  31404. return null;
  31405. }
  31406. return this._geometry.getVertexBuffer(kind);
  31407. };
  31408. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31409. if (!this._geometry) {
  31410. if (this._delayInfo) {
  31411. return this._delayInfo.indexOf(kind) !== -1;
  31412. }
  31413. return false;
  31414. }
  31415. return this._geometry.isVerticesDataPresent(kind);
  31416. };
  31417. /**
  31418. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31419. * Possible `kind` values :
  31420. * - BABYLON.VertexBuffer.PositionKind
  31421. * - BABYLON.VertexBuffer.UVKind
  31422. * - BABYLON.VertexBuffer.UV2Kind
  31423. * - BABYLON.VertexBuffer.UV3Kind
  31424. * - BABYLON.VertexBuffer.UV4Kind
  31425. * - BABYLON.VertexBuffer.UV5Kind
  31426. * - BABYLON.VertexBuffer.UV6Kind
  31427. * - BABYLON.VertexBuffer.ColorKind
  31428. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31429. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31430. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31431. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31432. */
  31433. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31434. if (!this._geometry) {
  31435. if (this._delayInfo) {
  31436. return this._delayInfo.indexOf(kind) !== -1;
  31437. }
  31438. return false;
  31439. }
  31440. return this._geometry.isVertexBufferUpdatable(kind);
  31441. };
  31442. /**
  31443. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31444. * Possible `kind` values :
  31445. * - BABYLON.VertexBuffer.PositionKind
  31446. * - BABYLON.VertexBuffer.UVKind
  31447. * - BABYLON.VertexBuffer.UV2Kind
  31448. * - BABYLON.VertexBuffer.UV3Kind
  31449. * - BABYLON.VertexBuffer.UV4Kind
  31450. * - BABYLON.VertexBuffer.UV5Kind
  31451. * - BABYLON.VertexBuffer.UV6Kind
  31452. * - BABYLON.VertexBuffer.ColorKind
  31453. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31454. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31455. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31456. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31457. */
  31458. Mesh.prototype.getVerticesDataKinds = function () {
  31459. if (!this._geometry) {
  31460. var result = new Array();
  31461. if (this._delayInfo) {
  31462. this._delayInfo.forEach(function (kind, index, array) {
  31463. result.push(kind);
  31464. });
  31465. }
  31466. return result;
  31467. }
  31468. return this._geometry.getVerticesDataKinds();
  31469. };
  31470. /**
  31471. * Returns a positive integer : the total number of indices in this mesh geometry.
  31472. * Returns zero if the mesh has no geometry.
  31473. */
  31474. Mesh.prototype.getTotalIndices = function () {
  31475. if (!this._geometry) {
  31476. return 0;
  31477. }
  31478. return this._geometry.getTotalIndices();
  31479. };
  31480. /**
  31481. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31482. * 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.
  31483. * Returns an empty array if the mesh has no geometry.
  31484. */
  31485. Mesh.prototype.getIndices = function (copyWhenShared) {
  31486. if (!this._geometry) {
  31487. return [];
  31488. }
  31489. return this._geometry.getIndices(copyWhenShared);
  31490. };
  31491. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31492. get: function () {
  31493. return this._masterMesh !== null && this._masterMesh !== undefined;
  31494. },
  31495. enumerable: true,
  31496. configurable: true
  31497. });
  31498. /**
  31499. * Determine if the current mesh is ready to be rendered
  31500. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31501. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31502. * @returns true if all associated assets are ready (material, textures, shaders)
  31503. */
  31504. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31505. if (completeCheck === void 0) { completeCheck = false; }
  31506. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31507. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31508. return false;
  31509. }
  31510. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31511. return false;
  31512. }
  31513. if (!this.subMeshes || this.subMeshes.length === 0) {
  31514. return true;
  31515. }
  31516. if (!completeCheck) {
  31517. return true;
  31518. }
  31519. var engine = this.getEngine();
  31520. var scene = this.getScene();
  31521. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31522. this.computeWorldMatrix();
  31523. var mat = this.material || scene.defaultMaterial;
  31524. if (mat) {
  31525. if (mat.storeEffectOnSubMeshes) {
  31526. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31527. var subMesh = _a[_i];
  31528. var effectiveMaterial = subMesh.getMaterial();
  31529. if (effectiveMaterial) {
  31530. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31531. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31532. return false;
  31533. }
  31534. }
  31535. else {
  31536. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31537. return false;
  31538. }
  31539. }
  31540. }
  31541. }
  31542. }
  31543. else {
  31544. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31545. return false;
  31546. }
  31547. }
  31548. }
  31549. // Shadows
  31550. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31551. var light = _c[_b];
  31552. var generator = light.getShadowGenerator();
  31553. if (generator) {
  31554. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31555. var subMesh = _e[_d];
  31556. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31557. return false;
  31558. }
  31559. }
  31560. }
  31561. }
  31562. // LOD
  31563. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31564. var lod = _g[_f];
  31565. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31566. return false;
  31567. }
  31568. }
  31569. return true;
  31570. };
  31571. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31572. /**
  31573. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31574. * This property is pertinent only for updatable parametric shapes.
  31575. */
  31576. get: function () {
  31577. return this._areNormalsFrozen;
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. /**
  31583. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31584. * It has no effect at all on other shapes.
  31585. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31586. * Returns the Mesh.
  31587. */
  31588. Mesh.prototype.freezeNormals = function () {
  31589. this._areNormalsFrozen = true;
  31590. return this;
  31591. };
  31592. /**
  31593. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31594. * It has no effect at all on other shapes.
  31595. * It reactivates the mesh normals computation if it was previously frozen.
  31596. * Returns the Mesh.
  31597. */
  31598. Mesh.prototype.unfreezeNormals = function () {
  31599. this._areNormalsFrozen = false;
  31600. return this;
  31601. };
  31602. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31603. /**
  31604. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31605. */
  31606. set: function (count) {
  31607. this._overridenInstanceCount = count;
  31608. },
  31609. enumerable: true,
  31610. configurable: true
  31611. });
  31612. // Methods
  31613. Mesh.prototype._preActivate = function () {
  31614. var sceneRenderId = this.getScene().getRenderId();
  31615. if (this._preActivateId === sceneRenderId) {
  31616. return this;
  31617. }
  31618. this._preActivateId = sceneRenderId;
  31619. this._visibleInstances = null;
  31620. return this;
  31621. };
  31622. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31623. if (this._visibleInstances) {
  31624. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31625. }
  31626. return this;
  31627. };
  31628. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31629. if (!this._visibleInstances) {
  31630. this._visibleInstances = {};
  31631. this._visibleInstances.defaultRenderId = renderId;
  31632. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31633. }
  31634. if (!this._visibleInstances[renderId]) {
  31635. this._visibleInstances[renderId] = new Array();
  31636. }
  31637. this._visibleInstances[renderId].push(instance);
  31638. return this;
  31639. };
  31640. /**
  31641. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31642. * This means the mesh underlying bounding box and sphere are recomputed.
  31643. * Returns the Mesh.
  31644. */
  31645. Mesh.prototype.refreshBoundingInfo = function () {
  31646. return this._refreshBoundingInfo(false);
  31647. };
  31648. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31649. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31650. return this;
  31651. }
  31652. var data = this._getPositionData(applySkeleton);
  31653. if (data) {
  31654. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31655. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31656. }
  31657. if (this.subMeshes) {
  31658. for (var index = 0; index < this.subMeshes.length; index++) {
  31659. this.subMeshes[index].refreshBoundingInfo();
  31660. }
  31661. }
  31662. this._updateBoundingInfo();
  31663. return this;
  31664. };
  31665. Mesh.prototype._getPositionData = function (applySkeleton) {
  31666. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31667. if (data && applySkeleton && this.skeleton) {
  31668. data = BABYLON.Tools.Slice(data);
  31669. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31670. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31671. if (matricesWeightsData && matricesIndicesData) {
  31672. var needExtras = this.numBoneInfluencers > 4;
  31673. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31674. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31675. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31676. var tempVector = BABYLON.Tmp.Vector3[0];
  31677. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31678. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31679. var matWeightIdx = 0;
  31680. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31681. finalMatrix.reset();
  31682. var inf;
  31683. var weight;
  31684. for (inf = 0; inf < 4; inf++) {
  31685. weight = matricesWeightsData[matWeightIdx + inf];
  31686. if (weight > 0) {
  31687. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31688. finalMatrix.addToSelf(tempMatrix);
  31689. }
  31690. }
  31691. if (needExtras) {
  31692. for (inf = 0; inf < 4; inf++) {
  31693. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31694. if (weight > 0) {
  31695. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31696. finalMatrix.addToSelf(tempMatrix);
  31697. }
  31698. }
  31699. }
  31700. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31701. tempVector.toArray(data, index);
  31702. }
  31703. }
  31704. }
  31705. return data;
  31706. };
  31707. Mesh.prototype._createGlobalSubMesh = function (force) {
  31708. var totalVertices = this.getTotalVertices();
  31709. if (!totalVertices || !this.getIndices()) {
  31710. return null;
  31711. }
  31712. // Check if we need to recreate the submeshes
  31713. if (this.subMeshes && this.subMeshes.length > 0) {
  31714. var ib = this.getIndices();
  31715. if (!ib) {
  31716. return null;
  31717. }
  31718. var totalIndices = ib.length;
  31719. var needToRecreate = false;
  31720. if (force) {
  31721. needToRecreate = true;
  31722. }
  31723. else {
  31724. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31725. var submesh = _a[_i];
  31726. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31727. needToRecreate = true;
  31728. break;
  31729. }
  31730. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31731. needToRecreate = true;
  31732. break;
  31733. }
  31734. }
  31735. }
  31736. if (!needToRecreate) {
  31737. return this.subMeshes[0];
  31738. }
  31739. }
  31740. this.releaseSubMeshes();
  31741. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31742. };
  31743. Mesh.prototype.subdivide = function (count) {
  31744. if (count < 1) {
  31745. return;
  31746. }
  31747. var totalIndices = this.getTotalIndices();
  31748. var subdivisionSize = (totalIndices / count) | 0;
  31749. var offset = 0;
  31750. // Ensure that subdivisionSize is a multiple of 3
  31751. while (subdivisionSize % 3 !== 0) {
  31752. subdivisionSize++;
  31753. }
  31754. this.releaseSubMeshes();
  31755. for (var index = 0; index < count; index++) {
  31756. if (offset >= totalIndices) {
  31757. break;
  31758. }
  31759. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31760. offset += subdivisionSize;
  31761. }
  31762. this.synchronizeInstances();
  31763. };
  31764. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31765. if (updatable === void 0) { updatable = false; }
  31766. if (!this._geometry) {
  31767. var vertexData = new BABYLON.VertexData();
  31768. vertexData.set(data, kind);
  31769. var scene = this.getScene();
  31770. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31771. }
  31772. else {
  31773. this._geometry.setVerticesData(kind, data, updatable, stride);
  31774. }
  31775. return this;
  31776. };
  31777. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31778. if (updatable === void 0) { updatable = true; }
  31779. var vb = this.getVertexBuffer(kind);
  31780. if (!vb || vb.isUpdatable() === updatable) {
  31781. return;
  31782. }
  31783. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31784. };
  31785. /**
  31786. * Sets the mesh VertexBuffer.
  31787. * Returns the Mesh.
  31788. */
  31789. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31790. if (!this._geometry) {
  31791. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31792. }
  31793. this._geometry.setVerticesBuffer(buffer);
  31794. return this;
  31795. };
  31796. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31797. if (!this._geometry) {
  31798. return this;
  31799. }
  31800. if (!makeItUnique) {
  31801. this._geometry.updateVerticesData(kind, data, updateExtends);
  31802. }
  31803. else {
  31804. this.makeGeometryUnique();
  31805. this.updateVerticesData(kind, data, updateExtends, false);
  31806. }
  31807. return this;
  31808. };
  31809. /**
  31810. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31811. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31812. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31813. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31814. * Returns the Mesh.
  31815. */
  31816. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31817. if (computeNormals === void 0) { computeNormals = true; }
  31818. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31819. if (!positions) {
  31820. return this;
  31821. }
  31822. positionFunction(positions);
  31823. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31824. if (computeNormals) {
  31825. var indices = this.getIndices();
  31826. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31827. if (!normals) {
  31828. return this;
  31829. }
  31830. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31831. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31832. }
  31833. return this;
  31834. };
  31835. /**
  31836. * Creates a un-shared specific occurence of the geometry for the mesh.
  31837. * Returns the Mesh.
  31838. */
  31839. Mesh.prototype.makeGeometryUnique = function () {
  31840. if (!this._geometry) {
  31841. return this;
  31842. }
  31843. var oldGeometry = this._geometry;
  31844. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31845. oldGeometry.releaseForMesh(this, true);
  31846. geometry.applyToMesh(this);
  31847. return this;
  31848. };
  31849. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31850. if (totalVertices === void 0) { totalVertices = null; }
  31851. if (updatable === void 0) { updatable = false; }
  31852. if (!this._geometry) {
  31853. var vertexData = new BABYLON.VertexData();
  31854. vertexData.indices = indices;
  31855. var scene = this.getScene();
  31856. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31857. }
  31858. else {
  31859. this._geometry.setIndices(indices, totalVertices, updatable);
  31860. }
  31861. return this;
  31862. };
  31863. /**
  31864. * Update the current index buffer
  31865. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31866. * Returns the Mesh.
  31867. */
  31868. Mesh.prototype.updateIndices = function (indices, offset) {
  31869. if (!this._geometry) {
  31870. return this;
  31871. }
  31872. this._geometry.updateIndices(indices, offset);
  31873. return this;
  31874. };
  31875. /**
  31876. * Invert the geometry to move from a right handed system to a left handed one.
  31877. * Returns the Mesh.
  31878. */
  31879. Mesh.prototype.toLeftHanded = function () {
  31880. if (!this._geometry) {
  31881. return this;
  31882. }
  31883. this._geometry.toLeftHanded();
  31884. return this;
  31885. };
  31886. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31887. if (!this._geometry) {
  31888. return this;
  31889. }
  31890. var engine = this.getScene().getEngine();
  31891. // Wireframe
  31892. var indexToBind;
  31893. if (this._unIndexed) {
  31894. indexToBind = null;
  31895. }
  31896. else {
  31897. switch (fillMode) {
  31898. case BABYLON.Material.PointFillMode:
  31899. indexToBind = null;
  31900. break;
  31901. case BABYLON.Material.WireFrameFillMode:
  31902. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31903. break;
  31904. default:
  31905. case BABYLON.Material.TriangleFillMode:
  31906. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31907. break;
  31908. }
  31909. }
  31910. // VBOs
  31911. this._geometry._bind(effect, indexToBind);
  31912. return this;
  31913. };
  31914. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31915. if (alternate === void 0) { alternate = false; }
  31916. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31917. return this;
  31918. }
  31919. this.onBeforeDrawObservable.notifyObservers(this);
  31920. var scene = this.getScene();
  31921. var engine = scene.getEngine();
  31922. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31923. // or triangles as points
  31924. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31925. }
  31926. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31927. // Triangles as wireframe
  31928. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31929. }
  31930. else {
  31931. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31932. }
  31933. if (scene._isAlternateRenderingEnabled && !alternate) {
  31934. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31935. if (!effect || !scene.activeCamera) {
  31936. return this;
  31937. }
  31938. scene._switchToAlternateCameraConfiguration(true);
  31939. this._effectiveMaterial.bindView(effect);
  31940. this._effectiveMaterial.bindViewProjection(effect);
  31941. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31942. this._draw(subMesh, fillMode, instancesCount, true);
  31943. engine.setViewport(scene.activeCamera.viewport);
  31944. scene._switchToAlternateCameraConfiguration(false);
  31945. this._effectiveMaterial.bindView(effect);
  31946. this._effectiveMaterial.bindViewProjection(effect);
  31947. }
  31948. return this;
  31949. };
  31950. /**
  31951. * Registers for this mesh a javascript function called just before the rendering process.
  31952. * This function is passed the current mesh.
  31953. * Return the Mesh.
  31954. */
  31955. Mesh.prototype.registerBeforeRender = function (func) {
  31956. this.onBeforeRenderObservable.add(func);
  31957. return this;
  31958. };
  31959. /**
  31960. * Disposes a previously registered javascript function called before the rendering.
  31961. * This function is passed the current mesh.
  31962. * Returns the Mesh.
  31963. */
  31964. Mesh.prototype.unregisterBeforeRender = function (func) {
  31965. this.onBeforeRenderObservable.removeCallback(func);
  31966. return this;
  31967. };
  31968. /**
  31969. * Registers for this mesh a javascript function called just after the rendering is complete.
  31970. * This function is passed the current mesh.
  31971. * Returns the Mesh.
  31972. */
  31973. Mesh.prototype.registerAfterRender = function (func) {
  31974. this.onAfterRenderObservable.add(func);
  31975. return this;
  31976. };
  31977. /**
  31978. * Disposes a previously registered javascript function called after the rendering.
  31979. * This function is passed the current mesh.
  31980. * Return the Mesh.
  31981. */
  31982. Mesh.prototype.unregisterAfterRender = function (func) {
  31983. this.onAfterRenderObservable.removeCallback(func);
  31984. return this;
  31985. };
  31986. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31987. var scene = this.getScene();
  31988. this._batchCache.mustReturn = false;
  31989. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31990. this._batchCache.visibleInstances[subMeshId] = null;
  31991. if (this._visibleInstances) {
  31992. var currentRenderId = scene.getRenderId();
  31993. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31994. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31995. var selfRenderId = this._renderId;
  31996. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31997. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31998. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31999. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32000. }
  32001. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32002. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32003. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32004. this._batchCache.mustReturn = true;
  32005. return this._batchCache;
  32006. }
  32007. if (currentRenderId !== selfRenderId) {
  32008. this._batchCache.renderSelf[subMeshId] = false;
  32009. }
  32010. }
  32011. this._renderIdForInstances[subMeshId] = currentRenderId;
  32012. }
  32013. return this._batchCache;
  32014. };
  32015. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32016. var visibleInstances = batch.visibleInstances[subMesh._id];
  32017. if (!visibleInstances) {
  32018. return this;
  32019. }
  32020. var matricesCount = visibleInstances.length + 1;
  32021. var bufferSize = matricesCount * 16 * 4;
  32022. var currentInstancesBufferSize = this._instancesBufferSize;
  32023. var instancesBuffer = this._instancesBuffer;
  32024. while (this._instancesBufferSize < bufferSize) {
  32025. this._instancesBufferSize *= 2;
  32026. }
  32027. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32028. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32029. }
  32030. var offset = 0;
  32031. var instancesCount = 0;
  32032. var world = this.getWorldMatrix();
  32033. if (batch.renderSelf[subMesh._id]) {
  32034. world.copyToArray(this._instancesData, offset);
  32035. offset += 16;
  32036. instancesCount++;
  32037. }
  32038. if (visibleInstances) {
  32039. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32040. var instance = visibleInstances[instanceIndex];
  32041. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32042. offset += 16;
  32043. instancesCount++;
  32044. }
  32045. }
  32046. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32047. if (instancesBuffer) {
  32048. instancesBuffer.dispose();
  32049. }
  32050. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32051. this._instancesBuffer = instancesBuffer;
  32052. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32053. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32054. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32055. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32056. }
  32057. else {
  32058. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32059. }
  32060. this._bind(subMesh, effect, fillMode);
  32061. this._draw(subMesh, fillMode, instancesCount);
  32062. engine.unbindInstanceAttributes();
  32063. return this;
  32064. };
  32065. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32066. var scene = this.getScene();
  32067. var engine = scene.getEngine();
  32068. if (hardwareInstancedRendering) {
  32069. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32070. }
  32071. else {
  32072. if (batch.renderSelf[subMesh._id]) {
  32073. // Draw
  32074. if (onBeforeDraw) {
  32075. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32076. }
  32077. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32078. }
  32079. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32080. if (visibleInstancesForSubMesh) {
  32081. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32082. var instance = visibleInstancesForSubMesh[instanceIndex];
  32083. // World
  32084. var world = instance.getWorldMatrix();
  32085. if (onBeforeDraw) {
  32086. onBeforeDraw(true, world, effectiveMaterial);
  32087. }
  32088. // Draw
  32089. this._draw(subMesh, fillMode);
  32090. }
  32091. }
  32092. }
  32093. return this;
  32094. };
  32095. /**
  32096. * 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
  32097. * @param subMesh defines the subMesh to render
  32098. * @param enableAlphaMode defines if alpha mode can be changed
  32099. * @returns the current mesh
  32100. */
  32101. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32102. this._checkOcclusionQuery();
  32103. if (this._isOccluded) {
  32104. return this;
  32105. }
  32106. var scene = this.getScene();
  32107. // Managing instances
  32108. var batch = this._getInstancesRenderList(subMesh._id);
  32109. if (batch.mustReturn) {
  32110. return this;
  32111. }
  32112. // Checking geometry state
  32113. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32114. return this;
  32115. }
  32116. this.onBeforeRenderObservable.notifyObservers(this);
  32117. var engine = scene.getEngine();
  32118. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32119. // Material
  32120. var material = subMesh.getMaterial();
  32121. if (!material) {
  32122. return this;
  32123. }
  32124. this._effectiveMaterial = material;
  32125. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32126. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32127. return this;
  32128. }
  32129. }
  32130. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32131. return this;
  32132. }
  32133. // Alpha mode
  32134. if (enableAlphaMode) {
  32135. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32136. }
  32137. // Outline - step 1
  32138. var savedDepthWrite = engine.getDepthWrite();
  32139. if (this.renderOutline) {
  32140. engine.setDepthWrite(false);
  32141. scene.getOutlineRenderer().render(subMesh, batch);
  32142. engine.setDepthWrite(savedDepthWrite);
  32143. }
  32144. var effect;
  32145. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32146. effect = subMesh.effect;
  32147. }
  32148. else {
  32149. effect = this._effectiveMaterial.getEffect();
  32150. }
  32151. if (!effect) {
  32152. return this;
  32153. }
  32154. var sideOrientation = this.overrideMaterialSideOrientation;
  32155. if (sideOrientation == null) {
  32156. sideOrientation = this._effectiveMaterial.sideOrientation;
  32157. if (this._getWorldMatrixDeterminant() < 0) {
  32158. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32159. }
  32160. }
  32161. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32162. if (this._effectiveMaterial.forceDepthWrite) {
  32163. engine.setDepthWrite(true);
  32164. }
  32165. // Bind
  32166. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32167. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32168. this._bind(subMesh, effect, fillMode);
  32169. }
  32170. var world = this.getWorldMatrix();
  32171. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32172. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32173. }
  32174. else {
  32175. this._effectiveMaterial.bind(world, this);
  32176. }
  32177. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32178. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32179. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32180. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32181. }
  32182. // Draw
  32183. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32184. // Unbind
  32185. this._effectiveMaterial.unbind();
  32186. // Outline - step 2
  32187. if (this.renderOutline && savedDepthWrite) {
  32188. engine.setDepthWrite(true);
  32189. engine.setColorWrite(false);
  32190. scene.getOutlineRenderer().render(subMesh, batch);
  32191. engine.setColorWrite(true);
  32192. }
  32193. // Overlay
  32194. if (this.renderOverlay) {
  32195. var currentMode = engine.getAlphaMode();
  32196. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32197. scene.getOutlineRenderer().render(subMesh, batch, true);
  32198. engine.setAlphaMode(currentMode);
  32199. }
  32200. this.onAfterRenderObservable.notifyObservers(this);
  32201. return this;
  32202. };
  32203. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32204. if (isInstance && effectiveMaterial) {
  32205. effectiveMaterial.bindOnlyWorldMatrix(world);
  32206. }
  32207. };
  32208. /**
  32209. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32210. */
  32211. Mesh.prototype.getEmittedParticleSystems = function () {
  32212. var results = new Array();
  32213. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32214. var particleSystem = this.getScene().particleSystems[index];
  32215. if (particleSystem.emitter === this) {
  32216. results.push(particleSystem);
  32217. }
  32218. }
  32219. return results;
  32220. };
  32221. /**
  32222. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32223. */
  32224. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32225. var results = new Array();
  32226. var descendants = this.getDescendants();
  32227. descendants.push(this);
  32228. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32229. var particleSystem = this.getScene().particleSystems[index];
  32230. var emitter = particleSystem.emitter;
  32231. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32232. results.push(particleSystem);
  32233. }
  32234. }
  32235. return results;
  32236. };
  32237. /**
  32238. * Normalize matrix weights so that all vertices have a total weight set to 1
  32239. */
  32240. Mesh.prototype.cleanMatrixWeights = function () {
  32241. var epsilon = 1e-3;
  32242. var noInfluenceBoneIndex = 0.0;
  32243. if (this.skeleton) {
  32244. noInfluenceBoneIndex = this.skeleton.bones.length;
  32245. }
  32246. else {
  32247. return;
  32248. }
  32249. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32250. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32251. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32252. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32253. var influencers = this.numBoneInfluencers;
  32254. var size = matricesWeights.length;
  32255. for (var i = 0; i < size; i += 4) {
  32256. var weight = 0.0;
  32257. var firstZeroWeight = -1;
  32258. for (var j = 0; j < 4; j++) {
  32259. var w = matricesWeights[i + j];
  32260. weight += w;
  32261. if (w < epsilon && firstZeroWeight < 0) {
  32262. firstZeroWeight = j;
  32263. }
  32264. }
  32265. if (matricesWeightsExtra) {
  32266. for (var j = 0; j < 4; j++) {
  32267. var w = matricesWeightsExtra[i + j];
  32268. weight += w;
  32269. if (w < epsilon && firstZeroWeight < 0) {
  32270. firstZeroWeight = j + 4;
  32271. }
  32272. }
  32273. }
  32274. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32275. firstZeroWeight = influencers - 1;
  32276. }
  32277. if (weight > epsilon) {
  32278. var mweight = 1.0 / weight;
  32279. for (var j = 0; j < 4; j++) {
  32280. matricesWeights[i + j] *= mweight;
  32281. }
  32282. if (matricesWeightsExtra) {
  32283. for (var j = 0; j < 4; j++) {
  32284. matricesWeightsExtra[i + j] *= mweight;
  32285. }
  32286. }
  32287. }
  32288. else {
  32289. if (firstZeroWeight >= 4) {
  32290. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32291. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32292. }
  32293. else {
  32294. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32295. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32296. }
  32297. }
  32298. }
  32299. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32300. if (matricesIndicesExtra) {
  32301. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32302. }
  32303. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32304. if (matricesWeightsExtra) {
  32305. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32306. }
  32307. };
  32308. Mesh.prototype._checkDelayState = function () {
  32309. var scene = this.getScene();
  32310. if (this._geometry) {
  32311. this._geometry.load(scene);
  32312. }
  32313. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32314. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32315. this._queueLoad(scene);
  32316. }
  32317. return this;
  32318. };
  32319. Mesh.prototype._queueLoad = function (scene) {
  32320. var _this = this;
  32321. scene._addPendingData(this);
  32322. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32323. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32324. if (data instanceof ArrayBuffer) {
  32325. _this._delayLoadingFunction(data, _this);
  32326. }
  32327. else {
  32328. _this._delayLoadingFunction(JSON.parse(data), _this);
  32329. }
  32330. _this.instances.forEach(function (instance) {
  32331. instance._syncSubMeshes();
  32332. });
  32333. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32334. scene._removePendingData(_this);
  32335. }, function () { }, scene.database, getBinaryData);
  32336. return this;
  32337. };
  32338. /**
  32339. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32340. */
  32341. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32342. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32343. return false;
  32344. }
  32345. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32346. return false;
  32347. }
  32348. this._checkDelayState();
  32349. return true;
  32350. };
  32351. /**
  32352. * Sets the mesh material by the material or multiMaterial `id` property.
  32353. * The material `id` is a string identifying the material or the multiMaterial.
  32354. * This method returns the Mesh.
  32355. */
  32356. Mesh.prototype.setMaterialByID = function (id) {
  32357. var materials = this.getScene().materials;
  32358. var index;
  32359. for (index = materials.length - 1; index > -1; index--) {
  32360. if (materials[index].id === id) {
  32361. this.material = materials[index];
  32362. return this;
  32363. }
  32364. }
  32365. // Multi
  32366. var multiMaterials = this.getScene().multiMaterials;
  32367. for (index = multiMaterials.length - 1; index > -1; index--) {
  32368. if (multiMaterials[index].id === id) {
  32369. this.material = multiMaterials[index];
  32370. return this;
  32371. }
  32372. }
  32373. return this;
  32374. };
  32375. /**
  32376. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32377. */
  32378. Mesh.prototype.getAnimatables = function () {
  32379. var results = new Array();
  32380. if (this.material) {
  32381. results.push(this.material);
  32382. }
  32383. if (this.skeleton) {
  32384. results.push(this.skeleton);
  32385. }
  32386. return results;
  32387. };
  32388. /**
  32389. * Modifies the mesh geometry according to the passed transformation matrix.
  32390. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32391. * The mesh normals are modified accordingly the same transformation.
  32392. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32393. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32394. * Returns the Mesh.
  32395. */
  32396. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32397. // Position
  32398. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32399. return this;
  32400. }
  32401. var submeshes = this.subMeshes.splice(0);
  32402. this._resetPointsArrayCache();
  32403. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32404. var temp = new Array();
  32405. var index;
  32406. for (index = 0; index < data.length; index += 3) {
  32407. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32408. }
  32409. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32410. // Normals
  32411. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32412. return this;
  32413. }
  32414. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32415. temp = [];
  32416. for (index = 0; index < data.length; index += 3) {
  32417. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32418. }
  32419. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32420. // flip faces?
  32421. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32422. this.flipFaces();
  32423. }
  32424. // Restore submeshes
  32425. this.releaseSubMeshes();
  32426. this.subMeshes = submeshes;
  32427. return this;
  32428. };
  32429. /**
  32430. * Modifies the mesh geometry according to its own current World Matrix.
  32431. * The mesh World Matrix is then reset.
  32432. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32433. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32434. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32435. * Returns the Mesh.
  32436. */
  32437. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32438. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32439. this.scaling.copyFromFloats(1, 1, 1);
  32440. this.position.copyFromFloats(0, 0, 0);
  32441. this.rotation.copyFromFloats(0, 0, 0);
  32442. //only if quaternion is already set
  32443. if (this.rotationQuaternion) {
  32444. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32445. }
  32446. this._worldMatrix = BABYLON.Matrix.Identity();
  32447. return this;
  32448. };
  32449. Object.defineProperty(Mesh.prototype, "_positions", {
  32450. // Cache
  32451. get: function () {
  32452. if (this._geometry) {
  32453. return this._geometry._positions;
  32454. }
  32455. return null;
  32456. },
  32457. enumerable: true,
  32458. configurable: true
  32459. });
  32460. Mesh.prototype._resetPointsArrayCache = function () {
  32461. if (this._geometry) {
  32462. this._geometry._resetPointsArrayCache();
  32463. }
  32464. return this;
  32465. };
  32466. Mesh.prototype._generatePointsArray = function () {
  32467. if (this._geometry) {
  32468. return this._geometry._generatePointsArray();
  32469. }
  32470. return false;
  32471. };
  32472. /**
  32473. * Returns a new Mesh object generated from the current mesh properties.
  32474. * This method must not get confused with createInstance().
  32475. * The parameter `name` is a string, the name given to the new mesh.
  32476. * The optional parameter `newParent` can be any Node object (default `null`).
  32477. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32478. * 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.
  32479. */
  32480. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32481. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32482. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32483. };
  32484. /**
  32485. * Releases resources associated with this mesh.
  32486. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32487. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32488. */
  32489. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32490. var _this = this;
  32491. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32492. this.morphTargetManager = null;
  32493. if (this._geometry) {
  32494. this._geometry.releaseForMesh(this, true);
  32495. }
  32496. // Sources
  32497. var meshes = this.getScene().meshes;
  32498. meshes.forEach(function (abstractMesh) {
  32499. var mesh = abstractMesh;
  32500. if (mesh._source && mesh._source === _this) {
  32501. mesh._source = null;
  32502. }
  32503. });
  32504. this._source = null;
  32505. // Instances
  32506. if (this._instancesBuffer) {
  32507. this._instancesBuffer.dispose();
  32508. this._instancesBuffer = null;
  32509. }
  32510. while (this.instances.length) {
  32511. this.instances[0].dispose();
  32512. }
  32513. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32514. };
  32515. /**
  32516. * Modifies the mesh geometry according to a displacement map.
  32517. * 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.
  32518. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32519. * This method returns nothing.
  32520. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32521. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32522. * 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.
  32523. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32524. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32525. *
  32526. * Returns the Mesh.
  32527. */
  32528. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32529. var _this = this;
  32530. var scene = this.getScene();
  32531. var onload = function (img) {
  32532. // Getting height map data
  32533. var canvas = document.createElement("canvas");
  32534. var context = canvas.getContext("2d");
  32535. var heightMapWidth = img.width;
  32536. var heightMapHeight = img.height;
  32537. canvas.width = heightMapWidth;
  32538. canvas.height = heightMapHeight;
  32539. context.drawImage(img, 0, 0);
  32540. // Create VertexData from map data
  32541. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32542. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32543. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32544. //execute success callback, if set
  32545. if (onSuccess) {
  32546. onSuccess(_this);
  32547. }
  32548. };
  32549. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32550. return this;
  32551. };
  32552. /**
  32553. * Modifies the mesh geometry according to a displacementMap buffer.
  32554. * 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.
  32555. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32556. * This method returns nothing.
  32557. * 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.
  32558. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32559. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32560. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32561. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32562. *
  32563. * Returns the Mesh.
  32564. */
  32565. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32566. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32567. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32568. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32569. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32570. return this;
  32571. }
  32572. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32574. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32575. var position = BABYLON.Vector3.Zero();
  32576. var normal = BABYLON.Vector3.Zero();
  32577. var uv = BABYLON.Vector2.Zero();
  32578. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32579. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32580. for (var index = 0; index < positions.length; index += 3) {
  32581. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32582. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32583. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32584. // Compute height
  32585. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32586. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32587. var pos = (u + v * heightMapWidth) * 4;
  32588. var r = buffer[pos] / 255.0;
  32589. var g = buffer[pos + 1] / 255.0;
  32590. var b = buffer[pos + 2] / 255.0;
  32591. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32592. normal.normalize();
  32593. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32594. position = position.add(normal);
  32595. position.toArray(positions, index);
  32596. }
  32597. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32598. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32599. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32600. return this;
  32601. };
  32602. /**
  32603. * Modify the mesh to get a flat shading rendering.
  32604. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32605. * This method returns the Mesh.
  32606. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32607. */
  32608. Mesh.prototype.convertToFlatShadedMesh = function () {
  32609. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32610. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32611. var kinds = this.getVerticesDataKinds();
  32612. var vbs = {};
  32613. var data = {};
  32614. var newdata = {};
  32615. var updatableNormals = false;
  32616. var kindIndex;
  32617. var kind;
  32618. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32619. kind = kinds[kindIndex];
  32620. var vertexBuffer = this.getVertexBuffer(kind);
  32621. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32622. updatableNormals = vertexBuffer.isUpdatable();
  32623. kinds.splice(kindIndex, 1);
  32624. kindIndex--;
  32625. continue;
  32626. }
  32627. vbs[kind] = vertexBuffer;
  32628. data[kind] = vbs[kind].getData();
  32629. newdata[kind] = [];
  32630. }
  32631. // Save previous submeshes
  32632. var previousSubmeshes = this.subMeshes.slice(0);
  32633. var indices = this.getIndices();
  32634. var totalIndices = this.getTotalIndices();
  32635. // Generating unique vertices per face
  32636. var index;
  32637. for (index = 0; index < totalIndices; index++) {
  32638. var vertexIndex = indices[index];
  32639. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32640. kind = kinds[kindIndex];
  32641. var stride = vbs[kind].getStrideSize();
  32642. for (var offset = 0; offset < stride; offset++) {
  32643. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32644. }
  32645. }
  32646. }
  32647. // Updating faces & normal
  32648. var normals = [];
  32649. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32650. for (index = 0; index < totalIndices; index += 3) {
  32651. indices[index] = index;
  32652. indices[index + 1] = index + 1;
  32653. indices[index + 2] = index + 2;
  32654. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32655. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32656. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32657. var p1p2 = p1.subtract(p2);
  32658. var p3p2 = p3.subtract(p2);
  32659. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32660. // Store same normals for every vertex
  32661. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32662. normals.push(normal.x);
  32663. normals.push(normal.y);
  32664. normals.push(normal.z);
  32665. }
  32666. }
  32667. this.setIndices(indices);
  32668. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32669. // Updating vertex buffers
  32670. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32671. kind = kinds[kindIndex];
  32672. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32673. }
  32674. // Updating submeshes
  32675. this.releaseSubMeshes();
  32676. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32677. var previousOne = previousSubmeshes[submeshIndex];
  32678. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32679. }
  32680. this.synchronizeInstances();
  32681. return this;
  32682. };
  32683. /**
  32684. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32685. * In other words, more vertices, no more indices and a single bigger VBO.
  32686. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32687. * Returns the Mesh.
  32688. */
  32689. Mesh.prototype.convertToUnIndexedMesh = function () {
  32690. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32691. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32692. var kinds = this.getVerticesDataKinds();
  32693. var vbs = {};
  32694. var data = {};
  32695. var newdata = {};
  32696. var kindIndex;
  32697. var kind;
  32698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32699. kind = kinds[kindIndex];
  32700. var vertexBuffer = this.getVertexBuffer(kind);
  32701. vbs[kind] = vertexBuffer;
  32702. data[kind] = vbs[kind].getData();
  32703. newdata[kind] = [];
  32704. }
  32705. // Save previous submeshes
  32706. var previousSubmeshes = this.subMeshes.slice(0);
  32707. var indices = this.getIndices();
  32708. var totalIndices = this.getTotalIndices();
  32709. // Generating unique vertices per face
  32710. var index;
  32711. for (index = 0; index < totalIndices; index++) {
  32712. var vertexIndex = indices[index];
  32713. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32714. kind = kinds[kindIndex];
  32715. var stride = vbs[kind].getStrideSize();
  32716. for (var offset = 0; offset < stride; offset++) {
  32717. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32718. }
  32719. }
  32720. }
  32721. // Updating indices
  32722. for (index = 0; index < totalIndices; index += 3) {
  32723. indices[index] = index;
  32724. indices[index + 1] = index + 1;
  32725. indices[index + 2] = index + 2;
  32726. }
  32727. this.setIndices(indices);
  32728. // Updating vertex buffers
  32729. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32730. kind = kinds[kindIndex];
  32731. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32732. }
  32733. // Updating submeshes
  32734. this.releaseSubMeshes();
  32735. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32736. var previousOne = previousSubmeshes[submeshIndex];
  32737. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32738. }
  32739. this._unIndexed = true;
  32740. this.synchronizeInstances();
  32741. return this;
  32742. };
  32743. /**
  32744. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32745. * This method returns the Mesh.
  32746. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32747. */
  32748. Mesh.prototype.flipFaces = function (flipNormals) {
  32749. if (flipNormals === void 0) { flipNormals = false; }
  32750. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32751. var i;
  32752. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32753. for (i = 0; i < vertex_data.normals.length; i++) {
  32754. vertex_data.normals[i] *= -1;
  32755. }
  32756. }
  32757. if (vertex_data.indices) {
  32758. var temp;
  32759. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32760. // reassign indices
  32761. temp = vertex_data.indices[i + 1];
  32762. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32763. vertex_data.indices[i + 2] = temp;
  32764. }
  32765. }
  32766. vertex_data.applyToMesh(this);
  32767. return this;
  32768. };
  32769. // Instances
  32770. /**
  32771. * Creates a new InstancedMesh object from the mesh model.
  32772. * An instance shares the same properties and the same material than its model.
  32773. * Only these properties of each instance can then be set individually :
  32774. * - position
  32775. * - rotation
  32776. * - rotationQuaternion
  32777. * - setPivotMatrix
  32778. * - scaling
  32779. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32780. * Warning : this method is not supported for Line mesh and LineSystem
  32781. */
  32782. Mesh.prototype.createInstance = function (name) {
  32783. return new BABYLON.InstancedMesh(name, this);
  32784. };
  32785. /**
  32786. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32787. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32788. * This method returns the Mesh.
  32789. */
  32790. Mesh.prototype.synchronizeInstances = function () {
  32791. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32792. var instance = this.instances[instanceIndex];
  32793. instance._syncSubMeshes();
  32794. }
  32795. return this;
  32796. };
  32797. /**
  32798. * Simplify the mesh according to the given array of settings.
  32799. * Function will return immediately and will simplify async. It returns the Mesh.
  32800. * @param settings a collection of simplification settings.
  32801. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32802. * @param type the type of simplification to run.
  32803. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32804. */
  32805. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32806. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32807. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32808. this.getScene().simplificationQueue.addTask({
  32809. settings: settings,
  32810. parallelProcessing: parallelProcessing,
  32811. mesh: this,
  32812. simplificationType: simplificationType,
  32813. successCallback: successCallback
  32814. });
  32815. return this;
  32816. };
  32817. /**
  32818. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32819. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32820. * This should be used together with the simplification to avoid disappearing triangles.
  32821. * Returns the Mesh.
  32822. * @param successCallback an optional success callback to be called after the optimization finished.
  32823. */
  32824. Mesh.prototype.optimizeIndices = function (successCallback) {
  32825. var _this = this;
  32826. var indices = this.getIndices();
  32827. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32828. if (!positions || !indices) {
  32829. return this;
  32830. }
  32831. var vectorPositions = new Array();
  32832. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32833. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32834. }
  32835. var dupes = new Array();
  32836. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32837. var realPos = vectorPositions.length - 1 - iteration;
  32838. var testedPosition = vectorPositions[realPos];
  32839. for (var j = 0; j < realPos; ++j) {
  32840. var againstPosition = vectorPositions[j];
  32841. if (testedPosition.equals(againstPosition)) {
  32842. dupes[realPos] = j;
  32843. break;
  32844. }
  32845. }
  32846. }, function () {
  32847. for (var i = 0; i < indices.length; ++i) {
  32848. indices[i] = dupes[indices[i]] || indices[i];
  32849. }
  32850. //indices are now reordered
  32851. var originalSubMeshes = _this.subMeshes.slice(0);
  32852. _this.setIndices(indices);
  32853. _this.subMeshes = originalSubMeshes;
  32854. if (successCallback) {
  32855. successCallback(_this);
  32856. }
  32857. });
  32858. return this;
  32859. };
  32860. Mesh.prototype.serialize = function (serializationObject) {
  32861. serializationObject.name = this.name;
  32862. serializationObject.id = this.id;
  32863. serializationObject.type = this.getClassName();
  32864. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32865. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32866. }
  32867. serializationObject.position = this.position.asArray();
  32868. if (this.rotationQuaternion) {
  32869. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32870. }
  32871. else if (this.rotation) {
  32872. serializationObject.rotation = this.rotation.asArray();
  32873. }
  32874. serializationObject.scaling = this.scaling.asArray();
  32875. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32876. serializationObject.isEnabled = this.isEnabled(false);
  32877. serializationObject.isVisible = this.isVisible;
  32878. serializationObject.infiniteDistance = this.infiniteDistance;
  32879. serializationObject.pickable = this.isPickable;
  32880. serializationObject.receiveShadows = this.receiveShadows;
  32881. serializationObject.billboardMode = this.billboardMode;
  32882. serializationObject.visibility = this.visibility;
  32883. serializationObject.checkCollisions = this.checkCollisions;
  32884. serializationObject.isBlocker = this.isBlocker;
  32885. // Parent
  32886. if (this.parent) {
  32887. serializationObject.parentId = this.parent.id;
  32888. }
  32889. // Geometry
  32890. serializationObject.isUnIndexed = this.isUnIndexed;
  32891. var geometry = this._geometry;
  32892. if (geometry) {
  32893. var geometryId = geometry.id;
  32894. serializationObject.geometryId = geometryId;
  32895. // SubMeshes
  32896. serializationObject.subMeshes = [];
  32897. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32898. var subMesh = this.subMeshes[subIndex];
  32899. serializationObject.subMeshes.push({
  32900. materialIndex: subMesh.materialIndex,
  32901. verticesStart: subMesh.verticesStart,
  32902. verticesCount: subMesh.verticesCount,
  32903. indexStart: subMesh.indexStart,
  32904. indexCount: subMesh.indexCount
  32905. });
  32906. }
  32907. }
  32908. // Material
  32909. if (this.material) {
  32910. serializationObject.materialId = this.material.id;
  32911. }
  32912. else {
  32913. this.material = null;
  32914. }
  32915. // Morph targets
  32916. if (this.morphTargetManager) {
  32917. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32918. }
  32919. // Skeleton
  32920. if (this.skeleton) {
  32921. serializationObject.skeletonId = this.skeleton.id;
  32922. }
  32923. // Physics
  32924. //TODO implement correct serialization for physics impostors.
  32925. var impostor = this.getPhysicsImpostor();
  32926. if (impostor) {
  32927. serializationObject.physicsMass = impostor.getParam("mass");
  32928. serializationObject.physicsFriction = impostor.getParam("friction");
  32929. serializationObject.physicsRestitution = impostor.getParam("mass");
  32930. serializationObject.physicsImpostor = impostor.type;
  32931. }
  32932. // Metadata
  32933. if (this.metadata) {
  32934. serializationObject.metadata = this.metadata;
  32935. }
  32936. // Instances
  32937. serializationObject.instances = [];
  32938. for (var index = 0; index < this.instances.length; index++) {
  32939. var instance = this.instances[index];
  32940. var serializationInstance = {
  32941. name: instance.name,
  32942. id: instance.id,
  32943. position: instance.position.asArray(),
  32944. scaling: instance.scaling.asArray()
  32945. };
  32946. if (instance.rotationQuaternion) {
  32947. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32948. }
  32949. else if (instance.rotation) {
  32950. serializationInstance.rotation = instance.rotation.asArray();
  32951. }
  32952. serializationObject.instances.push(serializationInstance);
  32953. // Animations
  32954. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32955. serializationInstance.ranges = instance.serializeAnimationRanges();
  32956. }
  32957. //
  32958. // Animations
  32959. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32960. serializationObject.ranges = this.serializeAnimationRanges();
  32961. // Layer mask
  32962. serializationObject.layerMask = this.layerMask;
  32963. // Alpha
  32964. serializationObject.alphaIndex = this.alphaIndex;
  32965. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32966. // Overlay
  32967. serializationObject.overlayAlpha = this.overlayAlpha;
  32968. serializationObject.overlayColor = this.overlayColor.asArray();
  32969. serializationObject.renderOverlay = this.renderOverlay;
  32970. // Fog
  32971. serializationObject.applyFog = this.applyFog;
  32972. // Action Manager
  32973. if (this.actionManager) {
  32974. serializationObject.actions = this.actionManager.serialize(this.name);
  32975. }
  32976. };
  32977. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32978. if (!this.geometry) {
  32979. return;
  32980. }
  32981. this._markSubMeshesAsAttributesDirty();
  32982. var morphTargetManager = this._morphTargetManager;
  32983. if (morphTargetManager && morphTargetManager.vertexCount) {
  32984. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32985. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32986. this.morphTargetManager = null;
  32987. return;
  32988. }
  32989. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32990. var morphTarget = morphTargetManager.getActiveTarget(index);
  32991. var positions = morphTarget.getPositions();
  32992. if (!positions) {
  32993. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32994. return;
  32995. }
  32996. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32997. var normals = morphTarget.getNormals();
  32998. if (normals) {
  32999. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33000. }
  33001. var tangents = morphTarget.getTangents();
  33002. if (tangents) {
  33003. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33004. }
  33005. }
  33006. }
  33007. else {
  33008. var index = 0;
  33009. // Positions
  33010. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33011. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33012. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33013. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33014. }
  33015. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33016. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33017. }
  33018. index++;
  33019. }
  33020. }
  33021. };
  33022. // Statics
  33023. /**
  33024. * Returns a new Mesh object parsed from the source provided.
  33025. * The parameter `parsedMesh` is the source.
  33026. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33027. */
  33028. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33029. var mesh;
  33030. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33031. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33032. }
  33033. else {
  33034. mesh = new Mesh(parsedMesh.name, scene);
  33035. }
  33036. mesh.id = parsedMesh.id;
  33037. if (BABYLON.Tags) {
  33038. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33039. }
  33040. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33041. if (parsedMesh.metadata !== undefined) {
  33042. mesh.metadata = parsedMesh.metadata;
  33043. }
  33044. if (parsedMesh.rotationQuaternion) {
  33045. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33046. }
  33047. else if (parsedMesh.rotation) {
  33048. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33049. }
  33050. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33051. if (parsedMesh.localMatrix) {
  33052. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33053. }
  33054. else if (parsedMesh.pivotMatrix) {
  33055. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33056. }
  33057. mesh.setEnabled(parsedMesh.isEnabled);
  33058. mesh.isVisible = parsedMesh.isVisible;
  33059. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33060. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33061. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33062. if (parsedMesh.applyFog !== undefined) {
  33063. mesh.applyFog = parsedMesh.applyFog;
  33064. }
  33065. if (parsedMesh.pickable !== undefined) {
  33066. mesh.isPickable = parsedMesh.pickable;
  33067. }
  33068. if (parsedMesh.alphaIndex !== undefined) {
  33069. mesh.alphaIndex = parsedMesh.alphaIndex;
  33070. }
  33071. mesh.receiveShadows = parsedMesh.receiveShadows;
  33072. mesh.billboardMode = parsedMesh.billboardMode;
  33073. if (parsedMesh.visibility !== undefined) {
  33074. mesh.visibility = parsedMesh.visibility;
  33075. }
  33076. mesh.checkCollisions = parsedMesh.checkCollisions;
  33077. if (parsedMesh.isBlocker !== undefined) {
  33078. mesh.isBlocker = parsedMesh.isBlocker;
  33079. }
  33080. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33081. // freezeWorldMatrix
  33082. if (parsedMesh.freezeWorldMatrix) {
  33083. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33084. }
  33085. // Parent
  33086. if (parsedMesh.parentId) {
  33087. mesh._waitingParentId = parsedMesh.parentId;
  33088. }
  33089. // Actions
  33090. if (parsedMesh.actions !== undefined) {
  33091. mesh._waitingActions = parsedMesh.actions;
  33092. }
  33093. // Overlay
  33094. if (parsedMesh.overlayAlpha !== undefined) {
  33095. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33096. }
  33097. if (parsedMesh.overlayColor !== undefined) {
  33098. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33099. }
  33100. if (parsedMesh.renderOverlay !== undefined) {
  33101. mesh.renderOverlay = parsedMesh.renderOverlay;
  33102. }
  33103. // Geometry
  33104. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33105. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33106. if (parsedMesh.delayLoadingFile) {
  33107. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33108. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33109. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33110. if (parsedMesh._binaryInfo) {
  33111. mesh._binaryInfo = parsedMesh._binaryInfo;
  33112. }
  33113. mesh._delayInfo = [];
  33114. if (parsedMesh.hasUVs) {
  33115. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33116. }
  33117. if (parsedMesh.hasUVs2) {
  33118. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33119. }
  33120. if (parsedMesh.hasUVs3) {
  33121. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33122. }
  33123. if (parsedMesh.hasUVs4) {
  33124. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33125. }
  33126. if (parsedMesh.hasUVs5) {
  33127. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33128. }
  33129. if (parsedMesh.hasUVs6) {
  33130. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33131. }
  33132. if (parsedMesh.hasColors) {
  33133. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33134. }
  33135. if (parsedMesh.hasMatricesIndices) {
  33136. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33137. }
  33138. if (parsedMesh.hasMatricesWeights) {
  33139. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33140. }
  33141. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33142. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33143. mesh._checkDelayState();
  33144. }
  33145. }
  33146. else {
  33147. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33148. }
  33149. // Material
  33150. if (parsedMesh.materialId) {
  33151. mesh.setMaterialByID(parsedMesh.materialId);
  33152. }
  33153. else {
  33154. mesh.material = null;
  33155. }
  33156. // Morph targets
  33157. if (parsedMesh.morphTargetManagerId > -1) {
  33158. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33159. }
  33160. // Skeleton
  33161. if (parsedMesh.skeletonId > -1) {
  33162. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33163. if (parsedMesh.numBoneInfluencers) {
  33164. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33165. }
  33166. }
  33167. // Animations
  33168. if (parsedMesh.animations) {
  33169. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33170. var parsedAnimation = parsedMesh.animations[animationIndex];
  33171. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33172. }
  33173. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33174. }
  33175. if (parsedMesh.autoAnimate) {
  33176. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33177. }
  33178. // Layer Mask
  33179. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33180. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33181. }
  33182. else {
  33183. mesh.layerMask = 0x0FFFFFFF;
  33184. }
  33185. // Physics
  33186. if (parsedMesh.physicsImpostor) {
  33187. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33188. mass: parsedMesh.physicsMass,
  33189. friction: parsedMesh.physicsFriction,
  33190. restitution: parsedMesh.physicsRestitution
  33191. }, scene);
  33192. }
  33193. // Instances
  33194. if (parsedMesh.instances) {
  33195. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33196. var parsedInstance = parsedMesh.instances[index];
  33197. var instance = mesh.createInstance(parsedInstance.name);
  33198. if (parsedInstance.id) {
  33199. instance.id = parsedInstance.id;
  33200. }
  33201. if (BABYLON.Tags) {
  33202. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33203. }
  33204. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33205. if (parsedInstance.parentId) {
  33206. instance._waitingParentId = parsedInstance.parentId;
  33207. }
  33208. if (parsedInstance.rotationQuaternion) {
  33209. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33210. }
  33211. else if (parsedInstance.rotation) {
  33212. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33213. }
  33214. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33215. instance.checkCollisions = mesh.checkCollisions;
  33216. if (parsedMesh.animations) {
  33217. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33218. parsedAnimation = parsedMesh.animations[animationIndex];
  33219. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33220. }
  33221. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33222. if (parsedMesh.autoAnimate) {
  33223. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33224. }
  33225. }
  33226. }
  33227. }
  33228. return mesh;
  33229. };
  33230. /**
  33231. * Creates a ribbon mesh.
  33232. * Please consider using the same method from the MeshBuilder class instead.
  33233. * 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.
  33234. *
  33235. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33236. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33237. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33238. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33239. * 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.
  33240. * 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.
  33241. * 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
  33242. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33243. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33244. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33245. */
  33246. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33247. if (closeArray === void 0) { closeArray = false; }
  33248. if (updatable === void 0) { updatable = false; }
  33249. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33250. pathArray: pathArray,
  33251. closeArray: closeArray,
  33252. closePath: closePath,
  33253. offset: offset,
  33254. updatable: updatable,
  33255. sideOrientation: sideOrientation,
  33256. instance: instance
  33257. }, scene);
  33258. };
  33259. /**
  33260. * Creates a plane polygonal mesh. By default, this is a disc.
  33261. * Please consider using the same method from the MeshBuilder class instead.
  33262. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33263. * 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.
  33264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33265. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33267. */
  33268. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33269. if (scene === void 0) { scene = null; }
  33270. var options = {
  33271. radius: radius,
  33272. tessellation: tessellation,
  33273. sideOrientation: sideOrientation,
  33274. updatable: updatable
  33275. };
  33276. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33277. };
  33278. /**
  33279. * Creates a box mesh.
  33280. * Please consider using the same method from the MeshBuilder class instead.
  33281. * The parameter `size` sets the size (float) of each box side (default 1).
  33282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33283. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33285. */
  33286. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33287. if (scene === void 0) { scene = null; }
  33288. var options = {
  33289. size: size,
  33290. sideOrientation: sideOrientation,
  33291. updatable: updatable
  33292. };
  33293. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33294. };
  33295. /**
  33296. * Creates a sphere mesh.
  33297. * Please consider using the same method from the MeshBuilder class instead.
  33298. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33299. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33301. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33303. */
  33304. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33305. var options = {
  33306. segments: segments,
  33307. diameterX: diameter,
  33308. diameterY: diameter,
  33309. diameterZ: diameter,
  33310. sideOrientation: sideOrientation,
  33311. updatable: updatable
  33312. };
  33313. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33314. };
  33315. /**
  33316. * Creates a cylinder or a cone mesh.
  33317. * Please consider using the same method from the MeshBuilder class instead.
  33318. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33319. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33320. * 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.
  33321. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33322. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33324. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33326. */
  33327. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33328. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33329. if (scene !== undefined) {
  33330. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33331. updatable = scene;
  33332. }
  33333. scene = subdivisions;
  33334. subdivisions = 1;
  33335. }
  33336. var options = {
  33337. height: height,
  33338. diameterTop: diameterTop,
  33339. diameterBottom: diameterBottom,
  33340. tessellation: tessellation,
  33341. subdivisions: subdivisions,
  33342. sideOrientation: sideOrientation,
  33343. updatable: updatable
  33344. };
  33345. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33346. };
  33347. // Torus (Code from SharpDX.org)
  33348. /**
  33349. * Creates a torus mesh.
  33350. * Please consider using the same method from the MeshBuilder class instead.
  33351. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33352. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33353. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33355. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33357. */
  33358. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33359. var options = {
  33360. diameter: diameter,
  33361. thickness: thickness,
  33362. tessellation: tessellation,
  33363. sideOrientation: sideOrientation,
  33364. updatable: updatable
  33365. };
  33366. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33367. };
  33368. /**
  33369. * Creates a torus knot mesh.
  33370. * Please consider using the same method from the MeshBuilder class instead.
  33371. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33372. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33373. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33374. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33380. var options = {
  33381. radius: radius,
  33382. tube: tube,
  33383. radialSegments: radialSegments,
  33384. tubularSegments: tubularSegments,
  33385. p: p,
  33386. q: q,
  33387. sideOrientation: sideOrientation,
  33388. updatable: updatable
  33389. };
  33390. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33391. };
  33392. /**
  33393. * Creates a line mesh.
  33394. * Please consider using the same method from the MeshBuilder class instead.
  33395. * 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.
  33396. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33397. * The parameter `points` is an array successive Vector3.
  33398. * 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
  33399. * When updating an instance, remember that only point positions can change, not the number of points.
  33400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33401. */
  33402. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33403. if (scene === void 0) { scene = null; }
  33404. if (updatable === void 0) { updatable = false; }
  33405. if (instance === void 0) { instance = null; }
  33406. var options = {
  33407. points: points,
  33408. updatable: updatable,
  33409. instance: instance
  33410. };
  33411. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33412. };
  33413. /**
  33414. * Creates a dashed line mesh.
  33415. * Please consider using the same method from the MeshBuilder class instead.
  33416. * 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.
  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 parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33420. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33421. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33422. * 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
  33423. * When updating an instance, remember that only point positions can change, not the number of points.
  33424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33425. */
  33426. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33427. if (scene === void 0) { scene = null; }
  33428. var options = {
  33429. points: points,
  33430. dashSize: dashSize,
  33431. gapSize: gapSize,
  33432. dashNb: dashNb,
  33433. updatable: updatable,
  33434. instance: instance
  33435. };
  33436. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33437. };
  33438. /**
  33439. * Creates a polygon mesh.
  33440. * Please consider using the same method from the MeshBuilder class instead.
  33441. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33442. * 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.
  33443. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33445. * Remember you can only change the shape positions, not their number when updating a polygon.
  33446. */
  33447. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33448. var options = {
  33449. shape: shape,
  33450. holes: holes,
  33451. updatable: updatable,
  33452. sideOrientation: sideOrientation
  33453. };
  33454. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33455. };
  33456. /**
  33457. * Creates an extruded polygon mesh, with depth in the Y direction.
  33458. * Please consider using the same method from the MeshBuilder class instead.
  33459. */
  33460. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33461. var options = {
  33462. shape: shape,
  33463. holes: holes,
  33464. depth: depth,
  33465. updatable: updatable,
  33466. sideOrientation: sideOrientation
  33467. };
  33468. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33469. };
  33470. /**
  33471. * Creates an extruded shape mesh.
  33472. * 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.
  33473. * Please consider using the same method from the MeshBuilder class instead.
  33474. *
  33475. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33476. * 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
  33477. * extruded along the Z axis.
  33478. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33479. * 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.
  33480. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33481. * 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
  33482. * 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
  33483. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33484. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33485. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33487. */
  33488. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33489. if (scene === void 0) { scene = null; }
  33490. var options = {
  33491. shape: shape,
  33492. path: path,
  33493. scale: scale,
  33494. rotation: rotation,
  33495. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33496. sideOrientation: sideOrientation,
  33497. instance: instance,
  33498. updatable: updatable
  33499. };
  33500. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33501. };
  33502. /**
  33503. * Creates an custom extruded shape mesh.
  33504. * 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.
  33505. * Please consider using the same method from the MeshBuilder class instead.
  33506. *
  33507. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33508. * 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
  33509. * extruded along the Z axis.
  33510. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33511. * 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
  33512. * and the distance of this point from the begining of the path :
  33513. * ```javascript
  33514. * var rotationFunction = function(i, distance) {
  33515. * // do things
  33516. * return rotationValue; }
  33517. * ```
  33518. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33519. * 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
  33520. * and the distance of this point from the begining of the path :
  33521. * ```javascript
  33522. * var scaleFunction = function(i, distance) {
  33523. * // do things
  33524. * return scaleValue;}
  33525. * ```
  33526. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33527. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33528. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33529. * 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
  33530. * 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
  33531. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33533. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33535. */
  33536. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33537. var options = {
  33538. shape: shape,
  33539. path: path,
  33540. scaleFunction: scaleFunction,
  33541. rotationFunction: rotationFunction,
  33542. ribbonCloseArray: ribbonCloseArray,
  33543. ribbonClosePath: ribbonClosePath,
  33544. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33545. sideOrientation: sideOrientation,
  33546. instance: instance,
  33547. updatable: updatable
  33548. };
  33549. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33550. };
  33551. /**
  33552. * Creates lathe mesh.
  33553. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33554. * Please consider using the same method from the MeshBuilder class instead.
  33555. * 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
  33556. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33557. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33558. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33560. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33562. */
  33563. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33564. var options = {
  33565. shape: shape,
  33566. radius: radius,
  33567. tessellation: tessellation,
  33568. sideOrientation: sideOrientation,
  33569. updatable: updatable
  33570. };
  33571. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33572. };
  33573. /**
  33574. * Creates a plane mesh.
  33575. * Please consider using the same method from the MeshBuilder class instead.
  33576. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33578. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33580. */
  33581. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33582. var options = {
  33583. size: size,
  33584. width: size,
  33585. height: size,
  33586. sideOrientation: sideOrientation,
  33587. updatable: updatable
  33588. };
  33589. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33590. };
  33591. /**
  33592. * Creates a ground mesh.
  33593. * Please consider using the same method from the MeshBuilder class instead.
  33594. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33595. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33597. */
  33598. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33599. var options = {
  33600. width: width,
  33601. height: height,
  33602. subdivisions: subdivisions,
  33603. updatable: updatable
  33604. };
  33605. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33606. };
  33607. /**
  33608. * Creates a tiled ground mesh.
  33609. * Please consider using the same method from the MeshBuilder class instead.
  33610. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33611. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33612. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33613. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33614. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33615. * numbers of subdivisions on the ground width and height of each tile.
  33616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33617. */
  33618. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33619. var options = {
  33620. xmin: xmin,
  33621. zmin: zmin,
  33622. xmax: xmax,
  33623. zmax: zmax,
  33624. subdivisions: subdivisions,
  33625. precision: precision,
  33626. updatable: updatable
  33627. };
  33628. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33629. };
  33630. /**
  33631. * Creates a ground mesh from a height map.
  33632. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33633. * Please consider using the same method from the MeshBuilder class instead.
  33634. * The parameter `url` sets the URL of the height map image resource.
  33635. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33636. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33637. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33638. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33639. * 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).
  33640. * This function is passed the newly built mesh :
  33641. * ```javascript
  33642. * function(mesh) { // do things
  33643. * return; }
  33644. * ```
  33645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33646. */
  33647. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33648. var options = {
  33649. width: width,
  33650. height: height,
  33651. subdivisions: subdivisions,
  33652. minHeight: minHeight,
  33653. maxHeight: maxHeight,
  33654. updatable: updatable,
  33655. onReady: onReady
  33656. };
  33657. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33658. };
  33659. /**
  33660. * Creates a tube mesh.
  33661. * 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.
  33662. * Please consider using the same method from the MeshBuilder class instead.
  33663. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33664. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33665. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33666. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33667. * 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.
  33668. * It must return a radius value (positive float) :
  33669. * ```javascript
  33670. * var radiusFunction = function(i, distance) {
  33671. * // do things
  33672. * return radius; }
  33673. * ```
  33674. * 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
  33675. * 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
  33676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33677. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33679. */
  33680. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33681. var options = {
  33682. path: path,
  33683. radius: radius,
  33684. tessellation: tessellation,
  33685. radiusFunction: radiusFunction,
  33686. arc: 1,
  33687. cap: cap,
  33688. updatable: updatable,
  33689. sideOrientation: sideOrientation,
  33690. instance: instance
  33691. };
  33692. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33693. };
  33694. /**
  33695. * Creates a polyhedron mesh.
  33696. * Please consider using the same method from the MeshBuilder class instead.
  33697. * 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
  33698. * to choose the wanted type.
  33699. * The parameter `size` (positive float, default 1) sets the polygon size.
  33700. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33701. * 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`.
  33702. * 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
  33703. * 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)`).
  33704. * 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
  33705. * 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.
  33706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33707. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33709. */
  33710. Mesh.CreatePolyhedron = function (name, options, scene) {
  33711. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33712. };
  33713. /**
  33714. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33715. * Please consider using the same method from the MeshBuilder class instead.
  33716. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33717. * 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`).
  33718. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33719. * 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.
  33720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33721. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33723. */
  33724. Mesh.CreateIcoSphere = function (name, options, scene) {
  33725. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33726. };
  33727. /**
  33728. * Creates a decal mesh.
  33729. * Please consider using the same method from the MeshBuilder class instead.
  33730. * 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.
  33731. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33732. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33733. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33734. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33735. */
  33736. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33737. var options = {
  33738. position: position,
  33739. normal: normal,
  33740. size: size,
  33741. angle: angle
  33742. };
  33743. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33744. };
  33745. // Skeletons
  33746. /**
  33747. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33748. */
  33749. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33750. if (!this._sourcePositions) {
  33751. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33752. if (!source) {
  33753. return this._sourcePositions;
  33754. }
  33755. this._sourcePositions = new Float32Array(source);
  33756. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33757. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33758. }
  33759. }
  33760. return this._sourcePositions;
  33761. };
  33762. /**
  33763. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33764. */
  33765. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33766. if (!this._sourceNormals) {
  33767. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33768. if (!source) {
  33769. return this._sourceNormals;
  33770. }
  33771. this._sourceNormals = new Float32Array(source);
  33772. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33773. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33774. }
  33775. }
  33776. return this._sourceNormals;
  33777. };
  33778. /**
  33779. * Updates the vertex buffer by applying transformation from the bones.
  33780. * Returns the Mesh.
  33781. *
  33782. * @param {skeleton} skeleton to apply
  33783. */
  33784. Mesh.prototype.applySkeleton = function (skeleton) {
  33785. if (!this.geometry) {
  33786. return this;
  33787. }
  33788. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33789. return this;
  33790. }
  33791. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33792. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33793. return this;
  33794. }
  33795. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33796. return this;
  33797. }
  33798. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33799. return this;
  33800. }
  33801. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33802. return this;
  33803. }
  33804. if (!this._sourcePositions) {
  33805. var submeshes = this.subMeshes.slice();
  33806. this.setPositionsForCPUSkinning();
  33807. this.subMeshes = submeshes;
  33808. }
  33809. if (!this._sourceNormals) {
  33810. this.setNormalsForCPUSkinning();
  33811. }
  33812. // positionsData checks for not being Float32Array will only pass at most once
  33813. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33814. if (!positionsData) {
  33815. return this;
  33816. }
  33817. if (!(positionsData instanceof Float32Array)) {
  33818. positionsData = new Float32Array(positionsData);
  33819. }
  33820. // normalsData checks for not being Float32Array will only pass at most once
  33821. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33822. if (!normalsData) {
  33823. return this;
  33824. }
  33825. if (!(normalsData instanceof Float32Array)) {
  33826. normalsData = new Float32Array(normalsData);
  33827. }
  33828. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33829. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33830. if (!matricesWeightsData || !matricesIndicesData) {
  33831. return this;
  33832. }
  33833. var needExtras = this.numBoneInfluencers > 4;
  33834. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33835. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33836. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33837. var tempVector3 = BABYLON.Vector3.Zero();
  33838. var finalMatrix = new BABYLON.Matrix();
  33839. var tempMatrix = new BABYLON.Matrix();
  33840. var matWeightIdx = 0;
  33841. var inf;
  33842. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33843. var weight;
  33844. for (inf = 0; inf < 4; inf++) {
  33845. weight = matricesWeightsData[matWeightIdx + inf];
  33846. if (weight > 0) {
  33847. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33848. finalMatrix.addToSelf(tempMatrix);
  33849. }
  33850. }
  33851. if (needExtras) {
  33852. for (inf = 0; inf < 4; inf++) {
  33853. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33854. if (weight > 0) {
  33855. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33856. finalMatrix.addToSelf(tempMatrix);
  33857. }
  33858. }
  33859. }
  33860. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33861. tempVector3.toArray(positionsData, index);
  33862. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33863. tempVector3.toArray(normalsData, index);
  33864. finalMatrix.reset();
  33865. }
  33866. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33867. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33868. return this;
  33869. };
  33870. // Tools
  33871. /**
  33872. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33873. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33874. */
  33875. Mesh.MinMax = function (meshes) {
  33876. var minVector = null;
  33877. var maxVector = null;
  33878. meshes.forEach(function (mesh, index, array) {
  33879. var boundingInfo = mesh.getBoundingInfo();
  33880. var boundingBox = boundingInfo.boundingBox;
  33881. if (!minVector || !maxVector) {
  33882. minVector = boundingBox.minimumWorld;
  33883. maxVector = boundingBox.maximumWorld;
  33884. }
  33885. else {
  33886. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33887. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33888. }
  33889. });
  33890. if (!minVector || !maxVector) {
  33891. return {
  33892. min: BABYLON.Vector3.Zero(),
  33893. max: BABYLON.Vector3.Zero()
  33894. };
  33895. }
  33896. return {
  33897. min: minVector,
  33898. max: maxVector
  33899. };
  33900. };
  33901. /**
  33902. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33903. */
  33904. Mesh.Center = function (meshesOrMinMaxVector) {
  33905. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33906. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33907. };
  33908. /**
  33909. * Merge the array of meshes into a single mesh for performance reasons.
  33910. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33911. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33912. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33913. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33914. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33915. */
  33916. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33917. if (disposeSource === void 0) { disposeSource = true; }
  33918. var index;
  33919. if (!allow32BitsIndices) {
  33920. var totalVertices = 0;
  33921. // Counting vertices
  33922. for (index = 0; index < meshes.length; index++) {
  33923. if (meshes[index]) {
  33924. totalVertices += meshes[index].getTotalVertices();
  33925. if (totalVertices > 65536) {
  33926. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33927. return null;
  33928. }
  33929. }
  33930. }
  33931. }
  33932. // Merge
  33933. var vertexData = null;
  33934. var otherVertexData;
  33935. var indiceArray = new Array();
  33936. var source = null;
  33937. for (index = 0; index < meshes.length; index++) {
  33938. if (meshes[index]) {
  33939. meshes[index].computeWorldMatrix(true);
  33940. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33941. otherVertexData.transform(meshes[index].getWorldMatrix());
  33942. if (vertexData) {
  33943. vertexData.merge(otherVertexData);
  33944. }
  33945. else {
  33946. vertexData = otherVertexData;
  33947. source = meshes[index];
  33948. }
  33949. if (subdivideWithSubMeshes) {
  33950. indiceArray.push(meshes[index].getTotalIndices());
  33951. }
  33952. }
  33953. }
  33954. source = source;
  33955. if (!meshSubclass) {
  33956. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33957. }
  33958. vertexData.applyToMesh(meshSubclass);
  33959. // Setting properties
  33960. meshSubclass.material = source.material;
  33961. meshSubclass.checkCollisions = source.checkCollisions;
  33962. // Cleaning
  33963. if (disposeSource) {
  33964. for (index = 0; index < meshes.length; index++) {
  33965. if (meshes[index]) {
  33966. meshes[index].dispose();
  33967. }
  33968. }
  33969. }
  33970. // Subdivide
  33971. if (subdivideWithSubMeshes) {
  33972. //-- removal of global submesh
  33973. meshSubclass.releaseSubMeshes();
  33974. index = 0;
  33975. var offset = 0;
  33976. //-- apply subdivision according to index table
  33977. while (index < indiceArray.length) {
  33978. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33979. offset += indiceArray[index];
  33980. index++;
  33981. }
  33982. }
  33983. return meshSubclass;
  33984. };
  33985. // Consts
  33986. Mesh._FRONTSIDE = 0;
  33987. Mesh._BACKSIDE = 1;
  33988. Mesh._DOUBLESIDE = 2;
  33989. Mesh._DEFAULTSIDE = 0;
  33990. Mesh._NO_CAP = 0;
  33991. Mesh._CAP_START = 1;
  33992. Mesh._CAP_END = 2;
  33993. Mesh._CAP_ALL = 3;
  33994. return Mesh;
  33995. }(BABYLON.AbstractMesh));
  33996. BABYLON.Mesh = Mesh;
  33997. })(BABYLON || (BABYLON = {}));
  33998. //# sourceMappingURL=babylon.mesh.js.map
  33999. var BABYLON;
  34000. (function (BABYLON) {
  34001. var BaseSubMesh = /** @class */ (function () {
  34002. function BaseSubMesh() {
  34003. }
  34004. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34005. get: function () {
  34006. return this._materialEffect;
  34007. },
  34008. enumerable: true,
  34009. configurable: true
  34010. });
  34011. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34012. if (defines === void 0) { defines = null; }
  34013. if (this._materialEffect === effect) {
  34014. if (!effect) {
  34015. this._materialDefines = null;
  34016. }
  34017. return;
  34018. }
  34019. this._materialDefines = defines;
  34020. this._materialEffect = effect;
  34021. };
  34022. return BaseSubMesh;
  34023. }());
  34024. BABYLON.BaseSubMesh = BaseSubMesh;
  34025. var SubMesh = /** @class */ (function (_super) {
  34026. __extends(SubMesh, _super);
  34027. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34028. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34029. var _this = _super.call(this) || this;
  34030. _this.materialIndex = materialIndex;
  34031. _this.verticesStart = verticesStart;
  34032. _this.verticesCount = verticesCount;
  34033. _this.indexStart = indexStart;
  34034. _this.indexCount = indexCount;
  34035. _this._renderId = 0;
  34036. _this._mesh = mesh;
  34037. _this._renderingMesh = renderingMesh || mesh;
  34038. mesh.subMeshes.push(_this);
  34039. _this._trianglePlanes = [];
  34040. _this._id = mesh.subMeshes.length - 1;
  34041. if (createBoundingBox) {
  34042. _this.refreshBoundingInfo();
  34043. mesh.computeWorldMatrix(true);
  34044. }
  34045. return _this;
  34046. }
  34047. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34048. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34049. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34050. };
  34051. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34052. get: function () {
  34053. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34054. },
  34055. enumerable: true,
  34056. configurable: true
  34057. });
  34058. /**
  34059. * Returns the submesh BoudingInfo object.
  34060. */
  34061. SubMesh.prototype.getBoundingInfo = function () {
  34062. if (this.IsGlobal) {
  34063. return this._mesh.getBoundingInfo();
  34064. }
  34065. return this._boundingInfo;
  34066. };
  34067. /**
  34068. * Sets the submesh BoundingInfo.
  34069. * Return the SubMesh.
  34070. */
  34071. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34072. this._boundingInfo = boundingInfo;
  34073. return this;
  34074. };
  34075. /**
  34076. * Returns the mesh of the current submesh.
  34077. */
  34078. SubMesh.prototype.getMesh = function () {
  34079. return this._mesh;
  34080. };
  34081. /**
  34082. * Returns the rendering mesh of the submesh.
  34083. */
  34084. SubMesh.prototype.getRenderingMesh = function () {
  34085. return this._renderingMesh;
  34086. };
  34087. /**
  34088. * Returns the submesh material.
  34089. */
  34090. SubMesh.prototype.getMaterial = function () {
  34091. var rootMaterial = this._renderingMesh.material;
  34092. if (rootMaterial === null || rootMaterial === undefined) {
  34093. return this._mesh.getScene().defaultMaterial;
  34094. }
  34095. else if (rootMaterial.getSubMaterial) {
  34096. var multiMaterial = rootMaterial;
  34097. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34098. if (this._currentMaterial !== effectiveMaterial) {
  34099. this._currentMaterial = effectiveMaterial;
  34100. this._materialDefines = null;
  34101. }
  34102. return effectiveMaterial;
  34103. }
  34104. return rootMaterial;
  34105. };
  34106. // Methods
  34107. /**
  34108. * Sets a new updated BoundingInfo object to the submesh.
  34109. * Returns the SubMesh.
  34110. */
  34111. SubMesh.prototype.refreshBoundingInfo = function () {
  34112. this._lastColliderWorldVertices = null;
  34113. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34114. return this;
  34115. }
  34116. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34117. if (!data) {
  34118. this._boundingInfo = this._mesh.getBoundingInfo();
  34119. return this;
  34120. }
  34121. var indices = this._renderingMesh.getIndices();
  34122. var extend;
  34123. //is this the only submesh?
  34124. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34125. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34126. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34127. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34128. }
  34129. else {
  34130. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34131. }
  34132. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34133. return this;
  34134. };
  34135. SubMesh.prototype._checkCollision = function (collider) {
  34136. var boundingInfo = this.getBoundingInfo();
  34137. return boundingInfo._checkCollision(collider);
  34138. };
  34139. /**
  34140. * Updates the submesh BoundingInfo.
  34141. * Returns the Submesh.
  34142. */
  34143. SubMesh.prototype.updateBoundingInfo = function (world) {
  34144. var boundingInfo = this.getBoundingInfo();
  34145. if (!boundingInfo) {
  34146. this.refreshBoundingInfo();
  34147. boundingInfo = this.getBoundingInfo();
  34148. }
  34149. boundingInfo.update(world);
  34150. return this;
  34151. };
  34152. /**
  34153. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34154. * Boolean returned.
  34155. */
  34156. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34157. var boundingInfo = this.getBoundingInfo();
  34158. if (!boundingInfo) {
  34159. return false;
  34160. }
  34161. return boundingInfo.isInFrustum(frustumPlanes);
  34162. };
  34163. /**
  34164. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34165. * Boolean returned.
  34166. */
  34167. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34168. var boundingInfo = this.getBoundingInfo();
  34169. if (!boundingInfo) {
  34170. return false;
  34171. }
  34172. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34173. };
  34174. /**
  34175. * Renders the submesh.
  34176. * Returns it.
  34177. */
  34178. SubMesh.prototype.render = function (enableAlphaMode) {
  34179. this._renderingMesh.render(this, enableAlphaMode);
  34180. return this;
  34181. };
  34182. /**
  34183. * Returns a new Index Buffer.
  34184. * Type returned : WebGLBuffer.
  34185. */
  34186. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34187. if (!this._linesIndexBuffer) {
  34188. var linesIndices = [];
  34189. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34190. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34191. }
  34192. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34193. this.linesIndexCount = linesIndices.length;
  34194. }
  34195. return this._linesIndexBuffer;
  34196. };
  34197. /**
  34198. * True is the passed Ray intersects the submesh bounding box.
  34199. * Boolean returned.
  34200. */
  34201. SubMesh.prototype.canIntersects = function (ray) {
  34202. var boundingInfo = this.getBoundingInfo();
  34203. if (!boundingInfo) {
  34204. return false;
  34205. }
  34206. return ray.intersectsBox(boundingInfo.boundingBox);
  34207. };
  34208. /**
  34209. * Returns an object IntersectionInfo.
  34210. */
  34211. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34212. var intersectInfo = null;
  34213. var material = this.getMaterial();
  34214. if (!material) {
  34215. return null;
  34216. }
  34217. switch (material.fillMode) {
  34218. case BABYLON.Material.PointListDrawMode:
  34219. case BABYLON.Material.LineListDrawMode:
  34220. case BABYLON.Material.LineLoopDrawMode:
  34221. case BABYLON.Material.LineStripDrawMode:
  34222. case BABYLON.Material.TriangleFanDrawMode:
  34223. case BABYLON.Material.TriangleStripDrawMode:
  34224. return null;
  34225. }
  34226. // LineMesh first as it's also a Mesh...
  34227. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34228. var lineMesh = this._mesh;
  34229. // Line test
  34230. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34231. var p0 = positions[indices[index]];
  34232. var p1 = positions[indices[index + 1]];
  34233. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34234. if (length < 0) {
  34235. continue;
  34236. }
  34237. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34238. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34239. if (fastCheck) {
  34240. break;
  34241. }
  34242. }
  34243. }
  34244. }
  34245. else {
  34246. // Triangles test
  34247. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34248. var p0 = positions[indices[index]];
  34249. var p1 = positions[indices[index + 1]];
  34250. var p2 = positions[indices[index + 2]];
  34251. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34252. if (currentIntersectInfo) {
  34253. if (currentIntersectInfo.distance < 0) {
  34254. continue;
  34255. }
  34256. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34257. intersectInfo = currentIntersectInfo;
  34258. intersectInfo.faceId = index / 3;
  34259. if (fastCheck) {
  34260. break;
  34261. }
  34262. }
  34263. }
  34264. }
  34265. }
  34266. return intersectInfo;
  34267. };
  34268. SubMesh.prototype._rebuild = function () {
  34269. if (this._linesIndexBuffer) {
  34270. this._linesIndexBuffer = null;
  34271. }
  34272. };
  34273. // Clone
  34274. /**
  34275. * Creates a new Submesh from the passed Mesh.
  34276. */
  34277. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34278. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34279. if (!this.IsGlobal) {
  34280. var boundingInfo = this.getBoundingInfo();
  34281. if (!boundingInfo) {
  34282. return result;
  34283. }
  34284. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34285. }
  34286. return result;
  34287. };
  34288. // Dispose
  34289. /**
  34290. * Disposes the Submesh.
  34291. * Returns nothing.
  34292. */
  34293. SubMesh.prototype.dispose = function () {
  34294. if (this._linesIndexBuffer) {
  34295. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34296. this._linesIndexBuffer = null;
  34297. }
  34298. // Remove from mesh
  34299. var index = this._mesh.subMeshes.indexOf(this);
  34300. this._mesh.subMeshes.splice(index, 1);
  34301. };
  34302. // Statics
  34303. /**
  34304. * Creates a new Submesh from the passed parameters :
  34305. * - materialIndex (integer) : the index of the main mesh material.
  34306. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34307. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34308. * - mesh (Mesh) : the main mesh to create the submesh from.
  34309. * - renderingMesh (optional Mesh) : rendering mesh.
  34310. */
  34311. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34312. var minVertexIndex = Number.MAX_VALUE;
  34313. var maxVertexIndex = -Number.MAX_VALUE;
  34314. renderingMesh = (renderingMesh || mesh);
  34315. var indices = renderingMesh.getIndices();
  34316. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34317. var vertexIndex = indices[index];
  34318. if (vertexIndex < minVertexIndex)
  34319. minVertexIndex = vertexIndex;
  34320. if (vertexIndex > maxVertexIndex)
  34321. maxVertexIndex = vertexIndex;
  34322. }
  34323. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34324. };
  34325. return SubMesh;
  34326. }(BaseSubMesh));
  34327. BABYLON.SubMesh = SubMesh;
  34328. })(BABYLON || (BABYLON = {}));
  34329. //# sourceMappingURL=babylon.subMesh.js.map
  34330. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34331. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34332. s = arguments[i];
  34333. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34334. t[p] = s[p];
  34335. }
  34336. return t;
  34337. };
  34338. var BABYLON;
  34339. (function (BABYLON) {
  34340. /**
  34341. * Manages the defines for the Material
  34342. */
  34343. var MaterialDefines = /** @class */ (function () {
  34344. function MaterialDefines() {
  34345. this._isDirty = true;
  34346. /** @hidden */
  34347. this._areLightsDirty = true;
  34348. /** @hidden */
  34349. this._areAttributesDirty = true;
  34350. /** @hidden */
  34351. this._areTexturesDirty = true;
  34352. /** @hidden */
  34353. this._areFresnelDirty = true;
  34354. /** @hidden */
  34355. this._areMiscDirty = true;
  34356. /** @hidden */
  34357. this._areImageProcessingDirty = true;
  34358. /** @hidden */
  34359. this._normals = false;
  34360. /** @hidden */
  34361. this._uvs = false;
  34362. /** @hidden */
  34363. this._needNormals = false;
  34364. /** @hidden */
  34365. this._needUVs = false;
  34366. }
  34367. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34368. /**
  34369. * Specifies if the material needs to be re-calculated
  34370. */
  34371. get: function () {
  34372. return this._isDirty;
  34373. },
  34374. enumerable: true,
  34375. configurable: true
  34376. });
  34377. /**
  34378. * Marks the material to indicate that it has been re-calculated
  34379. */
  34380. MaterialDefines.prototype.markAsProcessed = function () {
  34381. this._isDirty = false;
  34382. this._areAttributesDirty = false;
  34383. this._areTexturesDirty = false;
  34384. this._areFresnelDirty = false;
  34385. this._areLightsDirty = false;
  34386. this._areMiscDirty = false;
  34387. this._areImageProcessingDirty = false;
  34388. };
  34389. /**
  34390. * Marks the material to indicate that it needs to be re-calculated
  34391. */
  34392. MaterialDefines.prototype.markAsUnprocessed = function () {
  34393. this._isDirty = true;
  34394. };
  34395. /**
  34396. * Marks the material to indicate all of its defines need to be re-calculated
  34397. */
  34398. MaterialDefines.prototype.markAllAsDirty = function () {
  34399. this._areTexturesDirty = true;
  34400. this._areAttributesDirty = true;
  34401. this._areLightsDirty = true;
  34402. this._areFresnelDirty = true;
  34403. this._areMiscDirty = true;
  34404. this._areImageProcessingDirty = true;
  34405. this._isDirty = true;
  34406. };
  34407. /**
  34408. * Marks the material to indicate that image processing needs to be re-calculated
  34409. */
  34410. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34411. this._areImageProcessingDirty = true;
  34412. this._isDirty = true;
  34413. };
  34414. /**
  34415. * Marks the material to indicate the lights need to be re-calculated
  34416. */
  34417. MaterialDefines.prototype.markAsLightDirty = function () {
  34418. this._areLightsDirty = true;
  34419. this._isDirty = true;
  34420. };
  34421. /**
  34422. * Marks the attribute state as changed
  34423. */
  34424. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34425. this._areAttributesDirty = true;
  34426. this._isDirty = true;
  34427. };
  34428. /**
  34429. * Marks the texture state as changed
  34430. */
  34431. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34432. this._areTexturesDirty = true;
  34433. this._isDirty = true;
  34434. };
  34435. /**
  34436. * Marks the fresnel state as changed
  34437. */
  34438. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34439. this._areFresnelDirty = true;
  34440. this._isDirty = true;
  34441. };
  34442. /**
  34443. * Marks the misc state as changed
  34444. */
  34445. MaterialDefines.prototype.markAsMiscDirty = function () {
  34446. this._areMiscDirty = true;
  34447. this._isDirty = true;
  34448. };
  34449. /**
  34450. * Rebuilds the material defines
  34451. */
  34452. MaterialDefines.prototype.rebuild = function () {
  34453. if (this._keys) {
  34454. delete this._keys;
  34455. }
  34456. this._keys = [];
  34457. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34458. var key = _a[_i];
  34459. if (key[0] === "_") {
  34460. continue;
  34461. }
  34462. this._keys.push(key);
  34463. }
  34464. };
  34465. /**
  34466. * Specifies if two material defines are equal
  34467. * @param other - A material define instance to compare to
  34468. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34469. */
  34470. MaterialDefines.prototype.isEqual = function (other) {
  34471. if (this._keys.length !== other._keys.length) {
  34472. return false;
  34473. }
  34474. for (var index = 0; index < this._keys.length; index++) {
  34475. var prop = this._keys[index];
  34476. if (this[prop] !== other[prop]) {
  34477. return false;
  34478. }
  34479. }
  34480. return true;
  34481. };
  34482. /**
  34483. * Clones this instance's defines to another instance
  34484. * @param other - material defines to clone values to
  34485. */
  34486. MaterialDefines.prototype.cloneTo = function (other) {
  34487. if (this._keys.length !== other._keys.length) {
  34488. other._keys = this._keys.slice(0);
  34489. }
  34490. for (var index = 0; index < this._keys.length; index++) {
  34491. var prop = this._keys[index];
  34492. other[prop] = this[prop];
  34493. }
  34494. };
  34495. /**
  34496. * Resets the material define values
  34497. */
  34498. MaterialDefines.prototype.reset = function () {
  34499. for (var index = 0; index < this._keys.length; index++) {
  34500. var prop = this._keys[index];
  34501. var type = typeof this[prop];
  34502. switch (type) {
  34503. case "number":
  34504. this[prop] = 0;
  34505. break;
  34506. case "string":
  34507. this[prop] = "";
  34508. break;
  34509. default:
  34510. this[prop] = false;
  34511. break;
  34512. }
  34513. }
  34514. };
  34515. /**
  34516. * Converts the material define values to a string
  34517. * @returns - String of material define information
  34518. */
  34519. MaterialDefines.prototype.toString = function () {
  34520. var result = "";
  34521. for (var index = 0; index < this._keys.length; index++) {
  34522. var prop = this._keys[index];
  34523. var value = this[prop];
  34524. var type = typeof value;
  34525. switch (type) {
  34526. case "number":
  34527. case "string":
  34528. result += "#define " + prop + " " + value + "\n";
  34529. break;
  34530. default:
  34531. if (value) {
  34532. result += "#define " + prop + "\n";
  34533. }
  34534. break;
  34535. }
  34536. }
  34537. return result;
  34538. };
  34539. return MaterialDefines;
  34540. }());
  34541. BABYLON.MaterialDefines = MaterialDefines;
  34542. /**
  34543. * Base class for the main features of a material in Babylon.js
  34544. */
  34545. var Material = /** @class */ (function () {
  34546. /**
  34547. * Creates a material instance
  34548. * @param name defines the name of the material
  34549. * @param scene defines the scene to reference
  34550. * @param doNotAdd specifies if the material should be added to the scene
  34551. */
  34552. function Material(name, scene, doNotAdd) {
  34553. /**
  34554. * Specifies if the ready state should be checked on each call
  34555. */
  34556. this.checkReadyOnEveryCall = false;
  34557. /**
  34558. * Specifies if the ready state should be checked once
  34559. */
  34560. this.checkReadyOnlyOnce = false;
  34561. /**
  34562. * The state of the material
  34563. */
  34564. this.state = "";
  34565. /**
  34566. * The alpha value of the material
  34567. */
  34568. this._alpha = 1.0;
  34569. /**
  34570. * Specifies if back face culling is enabled
  34571. */
  34572. this._backFaceCulling = true;
  34573. /**
  34574. * Specifies if the material should be serialized
  34575. */
  34576. this.doNotSerialize = false;
  34577. /**
  34578. * Specifies if the effect should be stored on sub meshes
  34579. */
  34580. this.storeEffectOnSubMeshes = false;
  34581. /**
  34582. * An event triggered when the material is disposed
  34583. */
  34584. this.onDisposeObservable = new BABYLON.Observable();
  34585. /**
  34586. * An event triggered when the material is bound
  34587. */
  34588. this.onBindObservable = new BABYLON.Observable();
  34589. /**
  34590. * An event triggered when the material is unbound
  34591. */
  34592. this.onUnBindObservable = new BABYLON.Observable();
  34593. /**
  34594. * Stores the value of the alpha mode
  34595. */
  34596. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34597. /**
  34598. * Stores the state of the need depth pre-pass value
  34599. */
  34600. this._needDepthPrePass = false;
  34601. /**
  34602. * Specifies if depth writing should be disabled
  34603. */
  34604. this.disableDepthWrite = false;
  34605. /**
  34606. * Specifies if depth writing should be forced
  34607. */
  34608. this.forceDepthWrite = false;
  34609. /**
  34610. * Specifies if there should be a separate pass for culling
  34611. */
  34612. this.separateCullingPass = false;
  34613. /**
  34614. * Stores the state specifing if fog should be enabled
  34615. */
  34616. this._fogEnabled = true;
  34617. /**
  34618. * Stores the size of points
  34619. */
  34620. this.pointSize = 1.0;
  34621. /**
  34622. * Stores the z offset value
  34623. */
  34624. this.zOffset = 0;
  34625. /**
  34626. * Specifies if the material was previously ready
  34627. */
  34628. this._wasPreviouslyReady = false;
  34629. /**
  34630. * Stores the fill mode state
  34631. */
  34632. this._fillMode = Material.TriangleFillMode;
  34633. this.name = name;
  34634. this.id = name || BABYLON.Tools.RandomId();
  34635. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34636. this.uniqueId = this._scene.getUniqueId();
  34637. if (this._scene.useRightHandedSystem) {
  34638. this.sideOrientation = Material.ClockWiseSideOrientation;
  34639. }
  34640. else {
  34641. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34642. }
  34643. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34644. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34645. if (!doNotAdd) {
  34646. this._scene.materials.push(this);
  34647. }
  34648. }
  34649. Object.defineProperty(Material, "TriangleFillMode", {
  34650. /**
  34651. * Returns the triangle fill mode
  34652. */
  34653. get: function () {
  34654. return Material._TriangleFillMode;
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material, "WireFrameFillMode", {
  34660. /**
  34661. * Returns the wireframe mode
  34662. */
  34663. get: function () {
  34664. return Material._WireFrameFillMode;
  34665. },
  34666. enumerable: true,
  34667. configurable: true
  34668. });
  34669. Object.defineProperty(Material, "PointFillMode", {
  34670. /**
  34671. * Returns the point fill mode
  34672. */
  34673. get: function () {
  34674. return Material._PointFillMode;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material, "PointListDrawMode", {
  34680. /**
  34681. * Returns the point list draw mode
  34682. */
  34683. get: function () {
  34684. return Material._PointListDrawMode;
  34685. },
  34686. enumerable: true,
  34687. configurable: true
  34688. });
  34689. Object.defineProperty(Material, "LineListDrawMode", {
  34690. /**
  34691. * Returns the line list draw mode
  34692. */
  34693. get: function () {
  34694. return Material._LineListDrawMode;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "LineLoopDrawMode", {
  34700. /**
  34701. * Returns the line loop draw mode
  34702. */
  34703. get: function () {
  34704. return Material._LineLoopDrawMode;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "LineStripDrawMode", {
  34710. /**
  34711. * Returns the line strip draw mode
  34712. */
  34713. get: function () {
  34714. return Material._LineStripDrawMode;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34720. /**
  34721. * Returns the triangle strip draw mode
  34722. */
  34723. get: function () {
  34724. return Material._TriangleStripDrawMode;
  34725. },
  34726. enumerable: true,
  34727. configurable: true
  34728. });
  34729. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34730. /**
  34731. * Returns the triangle fan draw mode
  34732. */
  34733. get: function () {
  34734. return Material._TriangleFanDrawMode;
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34740. /**
  34741. * Returns the clock-wise side orientation
  34742. */
  34743. get: function () {
  34744. return Material._ClockWiseSideOrientation;
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34750. /**
  34751. * Returns the counter clock-wise side orientation
  34752. */
  34753. get: function () {
  34754. return Material._CounterClockWiseSideOrientation;
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. Object.defineProperty(Material, "TextureDirtyFlag", {
  34760. /**
  34761. * Returns the dirty texture flag value
  34762. */
  34763. get: function () {
  34764. return Material._TextureDirtyFlag;
  34765. },
  34766. enumerable: true,
  34767. configurable: true
  34768. });
  34769. Object.defineProperty(Material, "LightDirtyFlag", {
  34770. /**
  34771. * Returns the dirty light flag value
  34772. */
  34773. get: function () {
  34774. return Material._LightDirtyFlag;
  34775. },
  34776. enumerable: true,
  34777. configurable: true
  34778. });
  34779. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34780. /**
  34781. * Returns the dirty fresnel flag value
  34782. */
  34783. get: function () {
  34784. return Material._FresnelDirtyFlag;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34790. /**
  34791. * Returns the dirty attributes flag value
  34792. */
  34793. get: function () {
  34794. return Material._AttributesDirtyFlag;
  34795. },
  34796. enumerable: true,
  34797. configurable: true
  34798. });
  34799. Object.defineProperty(Material, "MiscDirtyFlag", {
  34800. /**
  34801. * Returns the dirty misc flag value
  34802. */
  34803. get: function () {
  34804. return Material._MiscDirtyFlag;
  34805. },
  34806. enumerable: true,
  34807. configurable: true
  34808. });
  34809. Object.defineProperty(Material.prototype, "alpha", {
  34810. /**
  34811. * Gets the alpha value of the material
  34812. */
  34813. get: function () {
  34814. return this._alpha;
  34815. },
  34816. /**
  34817. * Sets the alpha value of the material
  34818. */
  34819. set: function (value) {
  34820. if (this._alpha === value) {
  34821. return;
  34822. }
  34823. this._alpha = value;
  34824. this.markAsDirty(Material.MiscDirtyFlag);
  34825. },
  34826. enumerable: true,
  34827. configurable: true
  34828. });
  34829. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34830. /**
  34831. * Gets the back-face culling state
  34832. */
  34833. get: function () {
  34834. return this._backFaceCulling;
  34835. },
  34836. /**
  34837. * Sets the back-face culling state
  34838. */
  34839. set: function (value) {
  34840. if (this._backFaceCulling === value) {
  34841. return;
  34842. }
  34843. this._backFaceCulling = value;
  34844. this.markAsDirty(Material.TextureDirtyFlag);
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material.prototype, "onDispose", {
  34850. /**
  34851. * Called during a dispose event
  34852. */
  34853. set: function (callback) {
  34854. if (this._onDisposeObserver) {
  34855. this.onDisposeObservable.remove(this._onDisposeObserver);
  34856. }
  34857. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(Material.prototype, "onBind", {
  34863. /**
  34864. * Called during a bind event
  34865. */
  34866. set: function (callback) {
  34867. if (this._onBindObserver) {
  34868. this.onBindObservable.remove(this._onBindObserver);
  34869. }
  34870. this._onBindObserver = this.onBindObservable.add(callback);
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. Object.defineProperty(Material.prototype, "alphaMode", {
  34876. /**
  34877. * Gets the value of the alpha mode
  34878. */
  34879. get: function () {
  34880. return this._alphaMode;
  34881. },
  34882. /**
  34883. * Sets the value of the alpha mode.
  34884. *
  34885. * | Value | Type | Description |
  34886. * | --- | --- | --- |
  34887. * | 0 | ALPHA_DISABLE | |
  34888. * | 1 | ALPHA_ADD | |
  34889. * | 2 | ALPHA_COMBINE | |
  34890. * | 3 | ALPHA_SUBTRACT | |
  34891. * | 4 | ALPHA_MULTIPLY | |
  34892. * | 5 | ALPHA_MAXIMIZED | |
  34893. * | 6 | ALPHA_ONEONE | |
  34894. * | 7 | ALPHA_PREMULTIPLIED | |
  34895. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34896. * | 9 | ALPHA_INTERPOLATE | |
  34897. * | 10 | ALPHA_SCREENMODE | |
  34898. *
  34899. */
  34900. set: function (value) {
  34901. if (this._alphaMode === value) {
  34902. return;
  34903. }
  34904. this._alphaMode = value;
  34905. this.markAsDirty(Material.TextureDirtyFlag);
  34906. },
  34907. enumerable: true,
  34908. configurable: true
  34909. });
  34910. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34911. /**
  34912. * Gets the depth pre-pass value
  34913. */
  34914. get: function () {
  34915. return this._needDepthPrePass;
  34916. },
  34917. /**
  34918. * Sets the need depth pre-pass value
  34919. */
  34920. set: function (value) {
  34921. if (this._needDepthPrePass === value) {
  34922. return;
  34923. }
  34924. this._needDepthPrePass = value;
  34925. if (this._needDepthPrePass) {
  34926. this.checkReadyOnEveryCall = true;
  34927. }
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(Material.prototype, "fogEnabled", {
  34933. /**
  34934. * Gets the value of the fog enabled state
  34935. */
  34936. get: function () {
  34937. return this._fogEnabled;
  34938. },
  34939. /**
  34940. * Sets the state for enabling fog
  34941. */
  34942. set: function (value) {
  34943. if (this._fogEnabled === value) {
  34944. return;
  34945. }
  34946. this._fogEnabled = value;
  34947. this.markAsDirty(Material.MiscDirtyFlag);
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(Material.prototype, "wireframe", {
  34953. /**
  34954. * Gets a value specifying if wireframe mode is enabled
  34955. */
  34956. get: function () {
  34957. switch (this._fillMode) {
  34958. case Material.WireFrameFillMode:
  34959. case Material.LineListDrawMode:
  34960. case Material.LineLoopDrawMode:
  34961. case Material.LineStripDrawMode:
  34962. return true;
  34963. }
  34964. return this._scene.forceWireframe;
  34965. },
  34966. /**
  34967. * Sets the state of wireframe mode
  34968. */
  34969. set: function (value) {
  34970. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(Material.prototype, "pointsCloud", {
  34976. /**
  34977. * Gets the value specifying if point clouds are enabled
  34978. */
  34979. get: function () {
  34980. switch (this._fillMode) {
  34981. case Material.PointFillMode:
  34982. case Material.PointListDrawMode:
  34983. return true;
  34984. }
  34985. return this._scene.forcePointsCloud;
  34986. },
  34987. /**
  34988. * Sets the state of point cloud mode
  34989. */
  34990. set: function (value) {
  34991. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34992. },
  34993. enumerable: true,
  34994. configurable: true
  34995. });
  34996. Object.defineProperty(Material.prototype, "fillMode", {
  34997. /**
  34998. * Gets the material fill mode
  34999. */
  35000. get: function () {
  35001. return this._fillMode;
  35002. },
  35003. /**
  35004. * Sets the material fill mode
  35005. */
  35006. set: function (value) {
  35007. if (this._fillMode === value) {
  35008. return;
  35009. }
  35010. this._fillMode = value;
  35011. this.markAsDirty(Material.MiscDirtyFlag);
  35012. },
  35013. enumerable: true,
  35014. configurable: true
  35015. });
  35016. /**
  35017. * Returns a string representation of the current material
  35018. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35019. * @returns a string with material information
  35020. */
  35021. Material.prototype.toString = function (fullDetails) {
  35022. var ret = "Name: " + this.name;
  35023. if (fullDetails) {
  35024. }
  35025. return ret;
  35026. };
  35027. /**
  35028. * Gets the class name of the material
  35029. * @returns a string with the class name of the material
  35030. */
  35031. Material.prototype.getClassName = function () {
  35032. return "Material";
  35033. };
  35034. Object.defineProperty(Material.prototype, "isFrozen", {
  35035. /**
  35036. * Specifies if updates for the material been locked
  35037. */
  35038. get: function () {
  35039. return this.checkReadyOnlyOnce;
  35040. },
  35041. enumerable: true,
  35042. configurable: true
  35043. });
  35044. /**
  35045. * Locks updates for the material
  35046. */
  35047. Material.prototype.freeze = function () {
  35048. this.checkReadyOnlyOnce = true;
  35049. };
  35050. /**
  35051. * Unlocks updates for the material
  35052. */
  35053. Material.prototype.unfreeze = function () {
  35054. this.checkReadyOnlyOnce = false;
  35055. };
  35056. /**
  35057. * Specifies if the material is ready to be used
  35058. * @param mesh defines the mesh to check
  35059. * @param useInstances specifies if instances should be used
  35060. * @returns a boolean indicating if the material is ready to be used
  35061. */
  35062. Material.prototype.isReady = function (mesh, useInstances) {
  35063. return true;
  35064. };
  35065. /**
  35066. * Specifies that the submesh is ready to be used
  35067. * @param mesh defines the mesh to check
  35068. * @param subMesh defines which submesh to check
  35069. * @param useInstances specifies that instances should be used
  35070. * @returns a boolean indicating that the submesh is ready or not
  35071. */
  35072. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35073. return false;
  35074. };
  35075. /**
  35076. * Returns the material effect
  35077. * @returns the effect associated with the material
  35078. */
  35079. Material.prototype.getEffect = function () {
  35080. return this._effect;
  35081. };
  35082. /**
  35083. * Returns the current scene
  35084. * @returns a Scene
  35085. */
  35086. Material.prototype.getScene = function () {
  35087. return this._scene;
  35088. };
  35089. /**
  35090. * Specifies if the material will require alpha blending
  35091. * @returns a boolean specifying if alpha blending is needed
  35092. */
  35093. Material.prototype.needAlphaBlending = function () {
  35094. return (this.alpha < 1.0);
  35095. };
  35096. /**
  35097. * Specifies if the mesh will require alpha blending
  35098. * @param mesh defines the mesh to check
  35099. * @returns a boolean specifying if alpha blending is needed for the mesh
  35100. */
  35101. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35102. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35103. };
  35104. /**
  35105. * Specifies if this material should be rendered in alpha test mode
  35106. * @returns a boolean specifying if an alpha test is needed.
  35107. */
  35108. Material.prototype.needAlphaTesting = function () {
  35109. return false;
  35110. };
  35111. /**
  35112. * Gets the texture used for the alpha test
  35113. * @returns the texture to use for alpha testing
  35114. */
  35115. Material.prototype.getAlphaTestTexture = function () {
  35116. return null;
  35117. };
  35118. /**
  35119. * Marks the material to indicate that it needs to be re-calculated
  35120. */
  35121. Material.prototype.markDirty = function () {
  35122. this._wasPreviouslyReady = false;
  35123. };
  35124. /** @hidden */
  35125. Material.prototype._preBind = function (effect, overrideOrientation) {
  35126. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35127. var engine = this._scene.getEngine();
  35128. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35129. var reverse = orientation === Material.ClockWiseSideOrientation;
  35130. engine.enableEffect(effect ? effect : this._effect);
  35131. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35132. return reverse;
  35133. };
  35134. /**
  35135. * Binds the material to the mesh
  35136. * @param world defines the world transformation matrix
  35137. * @param mesh defines the mesh to bind the material to
  35138. */
  35139. Material.prototype.bind = function (world, mesh) {
  35140. };
  35141. /**
  35142. * Binds the submesh to the material
  35143. * @param world defines the world transformation matrix
  35144. * @param mesh defines the mesh containing the submesh
  35145. * @param subMesh defines the submesh to bind the material to
  35146. */
  35147. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35148. };
  35149. /**
  35150. * Binds the world matrix to the material
  35151. * @param world defines the world transformation matrix
  35152. */
  35153. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35154. };
  35155. /**
  35156. * Binds the scene's uniform buffer to the effect.
  35157. * @param effect defines the effect to bind to the scene uniform buffer
  35158. * @param sceneUbo defines the uniform buffer storing scene data
  35159. */
  35160. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35161. sceneUbo.bindToEffect(effect, "Scene");
  35162. };
  35163. /**
  35164. * Binds the view matrix to the effect
  35165. * @param effect defines the effect to bind the view matrix to
  35166. */
  35167. Material.prototype.bindView = function (effect) {
  35168. if (!this._useUBO) {
  35169. effect.setMatrix("view", this.getScene().getViewMatrix());
  35170. }
  35171. else {
  35172. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35173. }
  35174. };
  35175. /**
  35176. * Binds the view projection matrix to the effect
  35177. * @param effect defines the effect to bind the view projection matrix to
  35178. */
  35179. Material.prototype.bindViewProjection = function (effect) {
  35180. if (!this._useUBO) {
  35181. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35182. }
  35183. else {
  35184. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35185. }
  35186. };
  35187. /**
  35188. * Specifies if material alpha testing should be turned on for the mesh
  35189. * @param mesh defines the mesh to check
  35190. */
  35191. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35192. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35193. };
  35194. /**
  35195. * Processes to execute after binding the material to a mesh
  35196. * @param mesh defines the rendered mesh
  35197. */
  35198. Material.prototype._afterBind = function (mesh) {
  35199. this._scene._cachedMaterial = this;
  35200. if (mesh) {
  35201. this._scene._cachedVisibility = mesh.visibility;
  35202. }
  35203. else {
  35204. this._scene._cachedVisibility = 1;
  35205. }
  35206. if (mesh) {
  35207. this.onBindObservable.notifyObservers(mesh);
  35208. }
  35209. if (this.disableDepthWrite) {
  35210. var engine = this._scene.getEngine();
  35211. this._cachedDepthWriteState = engine.getDepthWrite();
  35212. engine.setDepthWrite(false);
  35213. }
  35214. };
  35215. /**
  35216. * Unbinds the material from the mesh
  35217. */
  35218. Material.prototype.unbind = function () {
  35219. this.onUnBindObservable.notifyObservers(this);
  35220. if (this.disableDepthWrite) {
  35221. var engine = this._scene.getEngine();
  35222. engine.setDepthWrite(this._cachedDepthWriteState);
  35223. }
  35224. };
  35225. /**
  35226. * Gets the active textures from the material
  35227. * @returns an array of textures
  35228. */
  35229. Material.prototype.getActiveTextures = function () {
  35230. return [];
  35231. };
  35232. /**
  35233. * Specifies if the material uses a texture
  35234. * @param texture defines the texture to check against the material
  35235. * @returns a boolean specifying if the material uses the texture
  35236. */
  35237. Material.prototype.hasTexture = function (texture) {
  35238. return false;
  35239. };
  35240. /**
  35241. * Makes a duplicate of the material, and gives it a new name
  35242. * @param name defines the new name for the duplicated material
  35243. * @returns the cloned material
  35244. */
  35245. Material.prototype.clone = function (name) {
  35246. return null;
  35247. };
  35248. /**
  35249. * Gets the meshes bound to the material
  35250. * @returns an array of meshes bound to the material
  35251. */
  35252. Material.prototype.getBindedMeshes = function () {
  35253. var result = new Array();
  35254. for (var index = 0; index < this._scene.meshes.length; index++) {
  35255. var mesh = this._scene.meshes[index];
  35256. if (mesh.material === this) {
  35257. result.push(mesh);
  35258. }
  35259. }
  35260. return result;
  35261. };
  35262. /**
  35263. * Force shader compilation
  35264. * @param mesh defines the mesh associated with this material
  35265. * @param onCompiled defines a function to execute once the material is compiled
  35266. * @param options defines the options to configure the compilation
  35267. */
  35268. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35269. var _this = this;
  35270. var localOptions = __assign({ clipPlane: false }, options);
  35271. var subMesh = new BABYLON.BaseSubMesh();
  35272. var scene = this.getScene();
  35273. var checkReady = function () {
  35274. if (!_this._scene || !_this._scene.getEngine()) {
  35275. return;
  35276. }
  35277. if (subMesh._materialDefines) {
  35278. subMesh._materialDefines._renderId = -1;
  35279. }
  35280. var clipPlaneState = scene.clipPlane;
  35281. if (localOptions.clipPlane) {
  35282. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35283. }
  35284. if (_this.storeEffectOnSubMeshes) {
  35285. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35286. if (onCompiled) {
  35287. onCompiled(_this);
  35288. }
  35289. }
  35290. else {
  35291. setTimeout(checkReady, 16);
  35292. }
  35293. }
  35294. else {
  35295. if (_this.isReady(mesh)) {
  35296. if (onCompiled) {
  35297. onCompiled(_this);
  35298. }
  35299. }
  35300. else {
  35301. setTimeout(checkReady, 16);
  35302. }
  35303. }
  35304. if (localOptions.clipPlane) {
  35305. scene.clipPlane = clipPlaneState;
  35306. }
  35307. };
  35308. checkReady();
  35309. };
  35310. /**
  35311. * Force shader compilation
  35312. * @param mesh defines the mesh that will use this material
  35313. * @param options defines additional options for compiling the shaders
  35314. * @returns a promise that resolves when the compilation completes
  35315. */
  35316. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35317. var _this = this;
  35318. return new Promise(function (resolve) {
  35319. _this.forceCompilation(mesh, function () {
  35320. resolve();
  35321. }, options);
  35322. });
  35323. };
  35324. /**
  35325. * Marks a define in the material to indicate that it needs to be re-computed
  35326. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35327. */
  35328. Material.prototype.markAsDirty = function (flag) {
  35329. if (flag & Material.TextureDirtyFlag) {
  35330. this._markAllSubMeshesAsTexturesDirty();
  35331. }
  35332. if (flag & Material.LightDirtyFlag) {
  35333. this._markAllSubMeshesAsLightsDirty();
  35334. }
  35335. if (flag & Material.FresnelDirtyFlag) {
  35336. this._markAllSubMeshesAsFresnelDirty();
  35337. }
  35338. if (flag & Material.AttributesDirtyFlag) {
  35339. this._markAllSubMeshesAsAttributesDirty();
  35340. }
  35341. if (flag & Material.MiscDirtyFlag) {
  35342. this._markAllSubMeshesAsMiscDirty();
  35343. }
  35344. this.getScene().resetCachedMaterial();
  35345. };
  35346. /**
  35347. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35348. * @param func defines a function which checks material defines against the submeshes
  35349. */
  35350. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35351. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35352. var mesh = _a[_i];
  35353. if (!mesh.subMeshes) {
  35354. continue;
  35355. }
  35356. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35357. var subMesh = _c[_b];
  35358. if (subMesh.getMaterial() !== this) {
  35359. continue;
  35360. }
  35361. if (!subMesh._materialDefines) {
  35362. continue;
  35363. }
  35364. func(subMesh._materialDefines);
  35365. }
  35366. }
  35367. };
  35368. /**
  35369. * Indicates that image processing needs to be re-calculated for all submeshes
  35370. */
  35371. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35372. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35373. };
  35374. /**
  35375. * Indicates that textures need to be re-calculated for all submeshes
  35376. */
  35377. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35378. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35379. };
  35380. /**
  35381. * Indicates that fresnel needs to be re-calculated for all submeshes
  35382. */
  35383. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35384. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35385. };
  35386. /**
  35387. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35388. */
  35389. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35390. this._markAllSubMeshesAsDirty(function (defines) {
  35391. defines.markAsFresnelDirty();
  35392. defines.markAsMiscDirty();
  35393. });
  35394. };
  35395. /**
  35396. * Indicates that lights need to be re-calculated for all submeshes
  35397. */
  35398. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35399. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35400. };
  35401. /**
  35402. * Indicates that attributes need to be re-calculated for all submeshes
  35403. */
  35404. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35405. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35406. };
  35407. /**
  35408. * Indicates that misc needs to be re-calculated for all submeshes
  35409. */
  35410. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35411. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35412. };
  35413. /**
  35414. * Indicates that textures and misc need to be re-calculated for all submeshes
  35415. */
  35416. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35417. this._markAllSubMeshesAsDirty(function (defines) {
  35418. defines.markAsTexturesDirty();
  35419. defines.markAsMiscDirty();
  35420. });
  35421. };
  35422. /**
  35423. * Disposes the material
  35424. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35425. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35426. */
  35427. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35428. // Animations
  35429. this.getScene().stopAnimation(this);
  35430. this.getScene().freeProcessedMaterials();
  35431. // Remove from scene
  35432. var index = this._scene.materials.indexOf(this);
  35433. if (index >= 0) {
  35434. this._scene.materials.splice(index, 1);
  35435. }
  35436. // Remove from meshes
  35437. for (index = 0; index < this._scene.meshes.length; index++) {
  35438. var mesh = this._scene.meshes[index];
  35439. if (mesh.material === this) {
  35440. mesh.material = null;
  35441. if (mesh.geometry) {
  35442. var geometry = (mesh.geometry);
  35443. if (this.storeEffectOnSubMeshes) {
  35444. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35445. var subMesh = _a[_i];
  35446. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35447. if (forceDisposeEffect && subMesh._materialEffect) {
  35448. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35449. }
  35450. }
  35451. }
  35452. else {
  35453. geometry._releaseVertexArrayObject(this._effect);
  35454. }
  35455. }
  35456. }
  35457. }
  35458. this._uniformBuffer.dispose();
  35459. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35460. if (forceDisposeEffect && this._effect) {
  35461. if (!this.storeEffectOnSubMeshes) {
  35462. this._scene.getEngine()._releaseEffect(this._effect);
  35463. }
  35464. this._effect = null;
  35465. }
  35466. // Callback
  35467. this.onDisposeObservable.notifyObservers(this);
  35468. this.onDisposeObservable.clear();
  35469. this.onBindObservable.clear();
  35470. this.onUnBindObservable.clear();
  35471. };
  35472. /**
  35473. * Serializes this material
  35474. * @returns the serialized material object
  35475. */
  35476. Material.prototype.serialize = function () {
  35477. return BABYLON.SerializationHelper.Serialize(this);
  35478. };
  35479. /**
  35480. * Creates a MultiMaterial from parsed MultiMaterial data.
  35481. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35482. * @param scene defines the hosting scene
  35483. * @returns a new MultiMaterial
  35484. */
  35485. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35486. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35487. multiMaterial.id = parsedMultiMaterial.id;
  35488. if (BABYLON.Tags) {
  35489. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35490. }
  35491. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35492. var subMatId = parsedMultiMaterial.materials[matIndex];
  35493. if (subMatId) {
  35494. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35495. }
  35496. else {
  35497. multiMaterial.subMaterials.push(null);
  35498. }
  35499. }
  35500. return multiMaterial;
  35501. };
  35502. /**
  35503. * Creates a material from parsed material data
  35504. * @param parsedMaterial defines parsed material data
  35505. * @param scene defines the hosting scene
  35506. * @param rootUrl defines the root URL to use to load textures
  35507. * @returns a new material
  35508. */
  35509. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35510. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35511. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35512. }
  35513. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35514. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35515. if (!BABYLON.LegacyPBRMaterial) {
  35516. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35517. return;
  35518. }
  35519. }
  35520. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35521. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35522. };
  35523. // Triangle views
  35524. Material._TriangleFillMode = 0;
  35525. Material._WireFrameFillMode = 1;
  35526. Material._PointFillMode = 2;
  35527. // Draw modes
  35528. Material._PointListDrawMode = 3;
  35529. Material._LineListDrawMode = 4;
  35530. Material._LineLoopDrawMode = 5;
  35531. Material._LineStripDrawMode = 6;
  35532. Material._TriangleStripDrawMode = 7;
  35533. Material._TriangleFanDrawMode = 8;
  35534. /**
  35535. * Stores the clock-wise side orientation
  35536. */
  35537. Material._ClockWiseSideOrientation = 0;
  35538. /**
  35539. * Stores the counter clock-wise side orientation
  35540. */
  35541. Material._CounterClockWiseSideOrientation = 1;
  35542. /**
  35543. * The dirty texture flag value
  35544. */
  35545. Material._TextureDirtyFlag = 1;
  35546. /**
  35547. * The dirty light flag value
  35548. */
  35549. Material._LightDirtyFlag = 2;
  35550. /**
  35551. * The dirty fresnel flag value
  35552. */
  35553. Material._FresnelDirtyFlag = 4;
  35554. /**
  35555. * The dirty attribute flag value
  35556. */
  35557. Material._AttributesDirtyFlag = 8;
  35558. /**
  35559. * The dirty misc flag value
  35560. */
  35561. Material._MiscDirtyFlag = 16;
  35562. __decorate([
  35563. BABYLON.serialize()
  35564. ], Material.prototype, "id", void 0);
  35565. __decorate([
  35566. BABYLON.serialize()
  35567. ], Material.prototype, "uniqueId", void 0);
  35568. __decorate([
  35569. BABYLON.serialize()
  35570. ], Material.prototype, "name", void 0);
  35571. __decorate([
  35572. BABYLON.serialize()
  35573. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35574. __decorate([
  35575. BABYLON.serialize()
  35576. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35577. __decorate([
  35578. BABYLON.serialize()
  35579. ], Material.prototype, "state", void 0);
  35580. __decorate([
  35581. BABYLON.serialize("alpha")
  35582. ], Material.prototype, "_alpha", void 0);
  35583. __decorate([
  35584. BABYLON.serialize("backFaceCulling")
  35585. ], Material.prototype, "_backFaceCulling", void 0);
  35586. __decorate([
  35587. BABYLON.serialize()
  35588. ], Material.prototype, "sideOrientation", void 0);
  35589. __decorate([
  35590. BABYLON.serialize("alphaMode")
  35591. ], Material.prototype, "_alphaMode", void 0);
  35592. __decorate([
  35593. BABYLON.serialize()
  35594. ], Material.prototype, "_needDepthPrePass", void 0);
  35595. __decorate([
  35596. BABYLON.serialize()
  35597. ], Material.prototype, "disableDepthWrite", void 0);
  35598. __decorate([
  35599. BABYLON.serialize()
  35600. ], Material.prototype, "forceDepthWrite", void 0);
  35601. __decorate([
  35602. BABYLON.serialize()
  35603. ], Material.prototype, "separateCullingPass", void 0);
  35604. __decorate([
  35605. BABYLON.serialize("fogEnabled")
  35606. ], Material.prototype, "_fogEnabled", void 0);
  35607. __decorate([
  35608. BABYLON.serialize()
  35609. ], Material.prototype, "pointSize", void 0);
  35610. __decorate([
  35611. BABYLON.serialize()
  35612. ], Material.prototype, "zOffset", void 0);
  35613. __decorate([
  35614. BABYLON.serialize()
  35615. ], Material.prototype, "wireframe", null);
  35616. __decorate([
  35617. BABYLON.serialize()
  35618. ], Material.prototype, "pointsCloud", null);
  35619. __decorate([
  35620. BABYLON.serialize()
  35621. ], Material.prototype, "fillMode", null);
  35622. return Material;
  35623. }());
  35624. BABYLON.Material = Material;
  35625. })(BABYLON || (BABYLON = {}));
  35626. //# sourceMappingURL=babylon.material.js.map
  35627. var BABYLON;
  35628. (function (BABYLON) {
  35629. var UniformBuffer = /** @class */ (function () {
  35630. /**
  35631. * Uniform buffer objects.
  35632. *
  35633. * Handles blocks of uniform on the GPU.
  35634. *
  35635. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35636. *
  35637. * For more information, please refer to :
  35638. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35639. */
  35640. function UniformBuffer(engine, data, dynamic) {
  35641. this._engine = engine;
  35642. this._noUBO = !engine.supportsUniformBuffers;
  35643. this._dynamic = dynamic;
  35644. this._data = data || [];
  35645. this._uniformLocations = {};
  35646. this._uniformSizes = {};
  35647. this._uniformLocationPointer = 0;
  35648. this._needSync = false;
  35649. if (this._noUBO) {
  35650. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35651. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35652. this.updateFloat = this._updateFloatForEffect;
  35653. this.updateFloat2 = this._updateFloat2ForEffect;
  35654. this.updateFloat3 = this._updateFloat3ForEffect;
  35655. this.updateFloat4 = this._updateFloat4ForEffect;
  35656. this.updateMatrix = this._updateMatrixForEffect;
  35657. this.updateVector3 = this._updateVector3ForEffect;
  35658. this.updateVector4 = this._updateVector4ForEffect;
  35659. this.updateColor3 = this._updateColor3ForEffect;
  35660. this.updateColor4 = this._updateColor4ForEffect;
  35661. }
  35662. else {
  35663. this._engine._uniformBuffers.push(this);
  35664. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35665. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35666. this.updateFloat = this._updateFloatForUniform;
  35667. this.updateFloat2 = this._updateFloat2ForUniform;
  35668. this.updateFloat3 = this._updateFloat3ForUniform;
  35669. this.updateFloat4 = this._updateFloat4ForUniform;
  35670. this.updateMatrix = this._updateMatrixForUniform;
  35671. this.updateVector3 = this._updateVector3ForUniform;
  35672. this.updateVector4 = this._updateVector4ForUniform;
  35673. this.updateColor3 = this._updateColor3ForUniform;
  35674. this.updateColor4 = this._updateColor4ForUniform;
  35675. }
  35676. }
  35677. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35678. // Properties
  35679. /**
  35680. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35681. * or just falling back on setUniformXXX calls.
  35682. */
  35683. get: function () {
  35684. return !this._noUBO;
  35685. },
  35686. enumerable: true,
  35687. configurable: true
  35688. });
  35689. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35690. /**
  35691. * Indicates if the WebGL underlying uniform buffer is in sync
  35692. * with the javascript cache data.
  35693. */
  35694. get: function () {
  35695. return !this._needSync;
  35696. },
  35697. enumerable: true,
  35698. configurable: true
  35699. });
  35700. /**
  35701. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35702. * Also, a dynamic UniformBuffer will disable cache verification and always
  35703. * update the underlying WebGL uniform buffer to the GPU.
  35704. */
  35705. UniformBuffer.prototype.isDynamic = function () {
  35706. return this._dynamic !== undefined;
  35707. };
  35708. /**
  35709. * The data cache on JS side.
  35710. */
  35711. UniformBuffer.prototype.getData = function () {
  35712. return this._bufferData;
  35713. };
  35714. /**
  35715. * The underlying WebGL Uniform buffer.
  35716. */
  35717. UniformBuffer.prototype.getBuffer = function () {
  35718. return this._buffer;
  35719. };
  35720. /**
  35721. * std140 layout specifies how to align data within an UBO structure.
  35722. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35723. * for specs.
  35724. */
  35725. UniformBuffer.prototype._fillAlignment = function (size) {
  35726. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35727. // and 4x4 matrices
  35728. // TODO : change if other types are used
  35729. var alignment;
  35730. if (size <= 2) {
  35731. alignment = size;
  35732. }
  35733. else {
  35734. alignment = 4;
  35735. }
  35736. if ((this._uniformLocationPointer % alignment) !== 0) {
  35737. var oldPointer = this._uniformLocationPointer;
  35738. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35739. var diff = this._uniformLocationPointer - oldPointer;
  35740. for (var i = 0; i < diff; i++) {
  35741. this._data.push(0);
  35742. }
  35743. }
  35744. };
  35745. /**
  35746. * Adds an uniform in the buffer.
  35747. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35748. * for the layout to be correct !
  35749. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35750. * @param {number|number[]} size Data size, or data directly.
  35751. */
  35752. UniformBuffer.prototype.addUniform = function (name, size) {
  35753. if (this._noUBO) {
  35754. return;
  35755. }
  35756. if (this._uniformLocations[name] !== undefined) {
  35757. // Already existing uniform
  35758. return;
  35759. }
  35760. // This function must be called in the order of the shader layout !
  35761. // size can be the size of the uniform, or data directly
  35762. var data;
  35763. if (size instanceof Array) {
  35764. data = size;
  35765. size = data.length;
  35766. }
  35767. else {
  35768. size = size;
  35769. data = [];
  35770. // Fill with zeros
  35771. for (var i = 0; i < size; i++) {
  35772. data.push(0);
  35773. }
  35774. }
  35775. this._fillAlignment(size);
  35776. this._uniformSizes[name] = size;
  35777. this._uniformLocations[name] = this._uniformLocationPointer;
  35778. this._uniformLocationPointer += size;
  35779. for (var i = 0; i < size; i++) {
  35780. this._data.push(data[i]);
  35781. }
  35782. this._needSync = true;
  35783. };
  35784. /**
  35785. * Wrapper for addUniform.
  35786. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35787. * @param {Matrix} mat A 4x4 matrix.
  35788. */
  35789. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35790. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35791. };
  35792. /**
  35793. * Wrapper for addUniform.
  35794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35795. * @param {number} x
  35796. * @param {number} y
  35797. */
  35798. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35799. var temp = [x, y];
  35800. this.addUniform(name, temp);
  35801. };
  35802. /**
  35803. * Wrapper for addUniform.
  35804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35805. * @param {number} x
  35806. * @param {number} y
  35807. * @param {number} z
  35808. */
  35809. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35810. var temp = [x, y, z];
  35811. this.addUniform(name, temp);
  35812. };
  35813. /**
  35814. * Wrapper for addUniform.
  35815. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35816. * @param {Color3} color
  35817. */
  35818. UniformBuffer.prototype.addColor3 = function (name, color) {
  35819. var temp = new Array();
  35820. color.toArray(temp);
  35821. this.addUniform(name, temp);
  35822. };
  35823. /**
  35824. * Wrapper for addUniform.
  35825. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35826. * @param {Color3} color
  35827. * @param {number} alpha
  35828. */
  35829. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35830. var temp = new Array();
  35831. color.toArray(temp);
  35832. temp.push(alpha);
  35833. this.addUniform(name, temp);
  35834. };
  35835. /**
  35836. * Wrapper for addUniform.
  35837. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35838. * @param {Vector3} vector
  35839. */
  35840. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35841. var temp = new Array();
  35842. vector.toArray(temp);
  35843. this.addUniform(name, temp);
  35844. };
  35845. /**
  35846. * Wrapper for addUniform.
  35847. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35848. */
  35849. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35850. this.addUniform(name, 12);
  35851. };
  35852. /**
  35853. * Wrapper for addUniform.
  35854. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35855. */
  35856. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35857. this.addUniform(name, 8);
  35858. };
  35859. /**
  35860. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35861. */
  35862. UniformBuffer.prototype.create = function () {
  35863. if (this._noUBO) {
  35864. return;
  35865. }
  35866. if (this._buffer) {
  35867. return; // nothing to do
  35868. }
  35869. // See spec, alignment must be filled as a vec4
  35870. this._fillAlignment(4);
  35871. this._bufferData = new Float32Array(this._data);
  35872. this._rebuild();
  35873. this._needSync = true;
  35874. };
  35875. UniformBuffer.prototype._rebuild = function () {
  35876. if (this._noUBO) {
  35877. return;
  35878. }
  35879. if (this._dynamic) {
  35880. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35881. }
  35882. else {
  35883. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35884. }
  35885. };
  35886. /**
  35887. * Updates the WebGL Uniform Buffer on the GPU.
  35888. * If the `dynamic` flag is set to true, no cache comparison is done.
  35889. * Otherwise, the buffer will be updated only if the cache differs.
  35890. */
  35891. UniformBuffer.prototype.update = function () {
  35892. if (!this._buffer) {
  35893. this.create();
  35894. return;
  35895. }
  35896. if (!this._dynamic && !this._needSync) {
  35897. return;
  35898. }
  35899. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35900. this._needSync = false;
  35901. };
  35902. /**
  35903. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35904. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35905. * @param {number[]|Float32Array} data Flattened data
  35906. * @param {number} size Size of the data.
  35907. */
  35908. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35909. var location = this._uniformLocations[uniformName];
  35910. if (location === undefined) {
  35911. if (this._buffer) {
  35912. // Cannot add an uniform if the buffer is already created
  35913. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35914. return;
  35915. }
  35916. this.addUniform(uniformName, size);
  35917. location = this._uniformLocations[uniformName];
  35918. }
  35919. if (!this._buffer) {
  35920. this.create();
  35921. }
  35922. if (!this._dynamic) {
  35923. // Cache for static uniform buffers
  35924. var changed = false;
  35925. for (var i = 0; i < size; i++) {
  35926. if (this._bufferData[location + i] !== data[i]) {
  35927. changed = true;
  35928. this._bufferData[location + i] = data[i];
  35929. }
  35930. }
  35931. this._needSync = this._needSync || changed;
  35932. }
  35933. else {
  35934. // No cache for dynamic
  35935. for (var i = 0; i < size; i++) {
  35936. this._bufferData[location + i] = data[i];
  35937. }
  35938. }
  35939. };
  35940. // Update methods
  35941. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35942. // To match std140, matrix must be realigned
  35943. for (var i = 0; i < 3; i++) {
  35944. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35945. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35946. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35947. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35948. }
  35949. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35950. };
  35951. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35952. this._currentEffect.setMatrix3x3(name, matrix);
  35953. };
  35954. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35955. this._currentEffect.setMatrix2x2(name, matrix);
  35956. };
  35957. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35958. // To match std140, matrix must be realigned
  35959. for (var i = 0; i < 2; i++) {
  35960. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35961. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35962. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35963. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35964. }
  35965. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35966. };
  35967. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35968. this._currentEffect.setFloat(name, x);
  35969. };
  35970. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35971. UniformBuffer._tempBuffer[0] = x;
  35972. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35973. };
  35974. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35975. if (suffix === void 0) { suffix = ""; }
  35976. this._currentEffect.setFloat2(name + suffix, x, y);
  35977. };
  35978. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35979. if (suffix === void 0) { suffix = ""; }
  35980. UniformBuffer._tempBuffer[0] = x;
  35981. UniformBuffer._tempBuffer[1] = y;
  35982. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35983. };
  35984. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35985. if (suffix === void 0) { suffix = ""; }
  35986. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35987. };
  35988. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35989. if (suffix === void 0) { suffix = ""; }
  35990. UniformBuffer._tempBuffer[0] = x;
  35991. UniformBuffer._tempBuffer[1] = y;
  35992. UniformBuffer._tempBuffer[2] = z;
  35993. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35994. };
  35995. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35996. if (suffix === void 0) { suffix = ""; }
  35997. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35998. };
  35999. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36000. if (suffix === void 0) { suffix = ""; }
  36001. UniformBuffer._tempBuffer[0] = x;
  36002. UniformBuffer._tempBuffer[1] = y;
  36003. UniformBuffer._tempBuffer[2] = z;
  36004. UniformBuffer._tempBuffer[3] = w;
  36005. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36006. };
  36007. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36008. this._currentEffect.setMatrix(name, mat);
  36009. };
  36010. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36011. this.updateUniform(name, mat.toArray(), 16);
  36012. };
  36013. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36014. this._currentEffect.setVector3(name, vector);
  36015. };
  36016. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36017. vector.toArray(UniformBuffer._tempBuffer);
  36018. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36019. };
  36020. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36021. this._currentEffect.setVector4(name, vector);
  36022. };
  36023. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36024. vector.toArray(UniformBuffer._tempBuffer);
  36025. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36026. };
  36027. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36028. if (suffix === void 0) { suffix = ""; }
  36029. this._currentEffect.setColor3(name + suffix, color);
  36030. };
  36031. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36032. if (suffix === void 0) { suffix = ""; }
  36033. color.toArray(UniformBuffer._tempBuffer);
  36034. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36035. };
  36036. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36037. if (suffix === void 0) { suffix = ""; }
  36038. this._currentEffect.setColor4(name + suffix, color, alpha);
  36039. };
  36040. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36041. if (suffix === void 0) { suffix = ""; }
  36042. color.toArray(UniformBuffer._tempBuffer);
  36043. UniformBuffer._tempBuffer[3] = alpha;
  36044. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36045. };
  36046. /**
  36047. * Sets a sampler uniform on the effect.
  36048. * @param {string} name Name of the sampler.
  36049. * @param {Texture} texture
  36050. */
  36051. UniformBuffer.prototype.setTexture = function (name, texture) {
  36052. this._currentEffect.setTexture(name, texture);
  36053. };
  36054. /**
  36055. * Directly updates the value of the uniform in the cache AND on the GPU.
  36056. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36057. * @param {number[]|Float32Array} data Flattened data
  36058. */
  36059. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36060. this.updateUniform(uniformName, data, data.length);
  36061. this.update();
  36062. };
  36063. /**
  36064. * Binds this uniform buffer to an effect.
  36065. * @param {Effect} effect
  36066. * @param {string} name Name of the uniform block in the shader.
  36067. */
  36068. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36069. this._currentEffect = effect;
  36070. if (this._noUBO || !this._buffer) {
  36071. return;
  36072. }
  36073. effect.bindUniformBuffer(this._buffer, name);
  36074. };
  36075. /**
  36076. * Disposes the uniform buffer.
  36077. */
  36078. UniformBuffer.prototype.dispose = function () {
  36079. if (this._noUBO) {
  36080. return;
  36081. }
  36082. var index = this._engine._uniformBuffers.indexOf(this);
  36083. if (index !== -1) {
  36084. this._engine._uniformBuffers.splice(index, 1);
  36085. }
  36086. if (!this._buffer) {
  36087. return;
  36088. }
  36089. if (this._engine._releaseBuffer(this._buffer)) {
  36090. this._buffer = null;
  36091. }
  36092. };
  36093. // Pool for avoiding memory leaks
  36094. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36095. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36096. return UniformBuffer;
  36097. }());
  36098. BABYLON.UniformBuffer = UniformBuffer;
  36099. })(BABYLON || (BABYLON = {}));
  36100. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36101. var BABYLON;
  36102. (function (BABYLON) {
  36103. /**
  36104. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36105. */
  36106. var VertexData = /** @class */ (function () {
  36107. function VertexData() {
  36108. }
  36109. /**
  36110. * Uses the passed data array to set the set the values for the specified kind of data
  36111. * @param data a linear array of floating numbers
  36112. * @param kind the type of data that is being set, eg positions, colors etc
  36113. */
  36114. VertexData.prototype.set = function (data, kind) {
  36115. switch (kind) {
  36116. case BABYLON.VertexBuffer.PositionKind:
  36117. this.positions = data;
  36118. break;
  36119. case BABYLON.VertexBuffer.NormalKind:
  36120. this.normals = data;
  36121. break;
  36122. case BABYLON.VertexBuffer.TangentKind:
  36123. this.tangents = data;
  36124. break;
  36125. case BABYLON.VertexBuffer.UVKind:
  36126. this.uvs = data;
  36127. break;
  36128. case BABYLON.VertexBuffer.UV2Kind:
  36129. this.uvs2 = data;
  36130. break;
  36131. case BABYLON.VertexBuffer.UV3Kind:
  36132. this.uvs3 = data;
  36133. break;
  36134. case BABYLON.VertexBuffer.UV4Kind:
  36135. this.uvs4 = data;
  36136. break;
  36137. case BABYLON.VertexBuffer.UV5Kind:
  36138. this.uvs5 = data;
  36139. break;
  36140. case BABYLON.VertexBuffer.UV6Kind:
  36141. this.uvs6 = data;
  36142. break;
  36143. case BABYLON.VertexBuffer.ColorKind:
  36144. this.colors = data;
  36145. break;
  36146. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36147. this.matricesIndices = data;
  36148. break;
  36149. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36150. this.matricesWeights = data;
  36151. break;
  36152. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36153. this.matricesIndicesExtra = data;
  36154. break;
  36155. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36156. this.matricesWeightsExtra = data;
  36157. break;
  36158. }
  36159. };
  36160. /**
  36161. * Associates the vertexData to the passed Mesh.
  36162. * Sets it as updatable or not (default `false`)
  36163. * @param mesh the mesh the vertexData is applied to
  36164. * @param updatable when used and having the value true allows new data to update the vertexData
  36165. * @returns the VertexData
  36166. */
  36167. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36168. this._applyTo(mesh, updatable);
  36169. return this;
  36170. };
  36171. /**
  36172. * Associates the vertexData to the passed Geometry.
  36173. * Sets it as updatable or not (default `false`)
  36174. * @param geometry the geometry the vertexData is applied to
  36175. * @param updatable when used and having the value true allows new data to update the vertexData
  36176. * @returns VertexData
  36177. */
  36178. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36179. this._applyTo(geometry, updatable);
  36180. return this;
  36181. };
  36182. /**
  36183. * Updates the associated mesh
  36184. * @param mesh the mesh to be updated
  36185. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36186. * @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
  36187. * @returns VertexData
  36188. */
  36189. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36190. this._update(mesh);
  36191. return this;
  36192. };
  36193. /**
  36194. * Updates the associated geometry
  36195. * @param geometry the geometry to be updated
  36196. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36197. * @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
  36198. * @returns VertexData.
  36199. */
  36200. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36201. this._update(geometry);
  36202. return this;
  36203. };
  36204. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36205. if (updatable === void 0) { updatable = false; }
  36206. if (this.positions) {
  36207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36208. }
  36209. if (this.normals) {
  36210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36211. }
  36212. if (this.tangents) {
  36213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36214. }
  36215. if (this.uvs) {
  36216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36217. }
  36218. if (this.uvs2) {
  36219. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36220. }
  36221. if (this.uvs3) {
  36222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36223. }
  36224. if (this.uvs4) {
  36225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36226. }
  36227. if (this.uvs5) {
  36228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36229. }
  36230. if (this.uvs6) {
  36231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36232. }
  36233. if (this.colors) {
  36234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36235. }
  36236. if (this.matricesIndices) {
  36237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36238. }
  36239. if (this.matricesWeights) {
  36240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36241. }
  36242. if (this.matricesIndicesExtra) {
  36243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36244. }
  36245. if (this.matricesWeightsExtra) {
  36246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36247. }
  36248. if (this.indices) {
  36249. meshOrGeometry.setIndices(this.indices, null, updatable);
  36250. }
  36251. else {
  36252. meshOrGeometry.setIndices([], null);
  36253. }
  36254. return this;
  36255. };
  36256. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36257. if (this.positions) {
  36258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36259. }
  36260. if (this.normals) {
  36261. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36262. }
  36263. if (this.tangents) {
  36264. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36265. }
  36266. if (this.uvs) {
  36267. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36268. }
  36269. if (this.uvs2) {
  36270. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36271. }
  36272. if (this.uvs3) {
  36273. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36274. }
  36275. if (this.uvs4) {
  36276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36277. }
  36278. if (this.uvs5) {
  36279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36280. }
  36281. if (this.uvs6) {
  36282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36283. }
  36284. if (this.colors) {
  36285. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36286. }
  36287. if (this.matricesIndices) {
  36288. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36289. }
  36290. if (this.matricesWeights) {
  36291. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36292. }
  36293. if (this.matricesIndicesExtra) {
  36294. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36295. }
  36296. if (this.matricesWeightsExtra) {
  36297. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36298. }
  36299. if (this.indices) {
  36300. meshOrGeometry.setIndices(this.indices, null);
  36301. }
  36302. return this;
  36303. };
  36304. /**
  36305. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36306. * @param matrix the transforming matrix
  36307. * @returns the VertexData
  36308. */
  36309. VertexData.prototype.transform = function (matrix) {
  36310. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36311. var transformed = BABYLON.Vector3.Zero();
  36312. var index;
  36313. if (this.positions) {
  36314. var position = BABYLON.Vector3.Zero();
  36315. for (index = 0; index < this.positions.length; index += 3) {
  36316. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36317. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36318. this.positions[index] = transformed.x;
  36319. this.positions[index + 1] = transformed.y;
  36320. this.positions[index + 2] = transformed.z;
  36321. }
  36322. }
  36323. if (this.normals) {
  36324. var normal = BABYLON.Vector3.Zero();
  36325. for (index = 0; index < this.normals.length; index += 3) {
  36326. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36327. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36328. this.normals[index] = transformed.x;
  36329. this.normals[index + 1] = transformed.y;
  36330. this.normals[index + 2] = transformed.z;
  36331. }
  36332. }
  36333. if (this.tangents) {
  36334. var tangent = BABYLON.Vector4.Zero();
  36335. var tangentTransformed = BABYLON.Vector4.Zero();
  36336. for (index = 0; index < this.tangents.length; index += 4) {
  36337. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36338. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36339. this.tangents[index] = tangentTransformed.x;
  36340. this.tangents[index + 1] = tangentTransformed.y;
  36341. this.tangents[index + 2] = tangentTransformed.z;
  36342. this.tangents[index + 3] = tangentTransformed.w;
  36343. }
  36344. }
  36345. if (flip && this.indices) {
  36346. for (index = 0; index < this.indices.length; index += 3) {
  36347. var tmp = this.indices[index + 1];
  36348. this.indices[index + 1] = this.indices[index + 2];
  36349. this.indices[index + 2] = tmp;
  36350. }
  36351. }
  36352. return this;
  36353. };
  36354. /**
  36355. * Merges the passed VertexData into the current one
  36356. * @param other the VertexData to be merged into the current one
  36357. * @returns the modified VertexData
  36358. */
  36359. VertexData.prototype.merge = function (other) {
  36360. this._validate();
  36361. other._validate();
  36362. if (!this.normals !== !other.normals ||
  36363. !this.tangents !== !other.tangents ||
  36364. !this.uvs !== !other.uvs ||
  36365. !this.uvs2 !== !other.uvs2 ||
  36366. !this.uvs3 !== !other.uvs3 ||
  36367. !this.uvs4 !== !other.uvs4 ||
  36368. !this.uvs5 !== !other.uvs5 ||
  36369. !this.uvs6 !== !other.uvs6 ||
  36370. !this.colors !== !other.colors ||
  36371. !this.matricesIndices !== !other.matricesIndices ||
  36372. !this.matricesWeights !== !other.matricesWeights ||
  36373. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36374. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36375. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36376. }
  36377. if (other.indices) {
  36378. if (!this.indices) {
  36379. this.indices = [];
  36380. }
  36381. var offset = this.positions ? this.positions.length / 3 : 0;
  36382. for (var index = 0; index < other.indices.length; index++) {
  36383. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36384. this.indices.push(other.indices[index] + offset);
  36385. }
  36386. }
  36387. this.positions = this._mergeElement(this.positions, other.positions);
  36388. this.normals = this._mergeElement(this.normals, other.normals);
  36389. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36390. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36391. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36392. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36393. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36394. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36395. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36396. this.colors = this._mergeElement(this.colors, other.colors);
  36397. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36398. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36399. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36400. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36401. return this;
  36402. };
  36403. VertexData.prototype._mergeElement = function (source, other) {
  36404. if (!source) {
  36405. return other;
  36406. }
  36407. if (!other) {
  36408. return source;
  36409. }
  36410. var len = other.length + source.length;
  36411. var isSrcTypedArray = source instanceof Float32Array;
  36412. var isOthTypedArray = other instanceof Float32Array;
  36413. // use non-loop method when the source is Float32Array
  36414. if (isSrcTypedArray) {
  36415. var ret32 = new Float32Array(len);
  36416. ret32.set(source);
  36417. ret32.set(other, source.length);
  36418. return ret32;
  36419. // source is number[], when other is also use concat
  36420. }
  36421. else if (!isOthTypedArray) {
  36422. return source.concat(other);
  36423. // source is a number[], but other is a Float32Array, loop required
  36424. }
  36425. else {
  36426. var ret = source.slice(0); // copy source to a separate array
  36427. for (var i = 0, len = other.length; i < len; i++) {
  36428. ret.push(other[i]);
  36429. }
  36430. return ret;
  36431. }
  36432. };
  36433. VertexData.prototype._validate = function () {
  36434. if (!this.positions) {
  36435. throw new Error("Positions are required");
  36436. }
  36437. var getElementCount = function (kind, values) {
  36438. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36439. if ((values.length % stride) !== 0) {
  36440. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36441. }
  36442. return values.length / stride;
  36443. };
  36444. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36445. var validateElementCount = function (kind, values) {
  36446. var elementCount = getElementCount(kind, values);
  36447. if (elementCount !== positionsElementCount) {
  36448. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36449. }
  36450. };
  36451. if (this.normals)
  36452. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36453. if (this.tangents)
  36454. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36455. if (this.uvs)
  36456. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36457. if (this.uvs2)
  36458. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36459. if (this.uvs3)
  36460. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36461. if (this.uvs4)
  36462. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36463. if (this.uvs5)
  36464. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36465. if (this.uvs6)
  36466. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36467. if (this.colors)
  36468. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36469. if (this.matricesIndices)
  36470. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36471. if (this.matricesWeights)
  36472. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36473. if (this.matricesIndicesExtra)
  36474. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36475. if (this.matricesWeightsExtra)
  36476. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36477. };
  36478. /**
  36479. * Serializes the VertexData
  36480. * @returns a serialized object
  36481. */
  36482. VertexData.prototype.serialize = function () {
  36483. var serializationObject = this.serialize();
  36484. if (this.positions) {
  36485. serializationObject.positions = this.positions;
  36486. }
  36487. if (this.normals) {
  36488. serializationObject.normals = this.normals;
  36489. }
  36490. if (this.tangents) {
  36491. serializationObject.tangents = this.tangents;
  36492. }
  36493. if (this.uvs) {
  36494. serializationObject.uvs = this.uvs;
  36495. }
  36496. if (this.uvs2) {
  36497. serializationObject.uvs2 = this.uvs2;
  36498. }
  36499. if (this.uvs3) {
  36500. serializationObject.uvs3 = this.uvs3;
  36501. }
  36502. if (this.uvs4) {
  36503. serializationObject.uvs4 = this.uvs4;
  36504. }
  36505. if (this.uvs5) {
  36506. serializationObject.uvs5 = this.uvs5;
  36507. }
  36508. if (this.uvs6) {
  36509. serializationObject.uvs6 = this.uvs6;
  36510. }
  36511. if (this.colors) {
  36512. serializationObject.colors = this.colors;
  36513. }
  36514. if (this.matricesIndices) {
  36515. serializationObject.matricesIndices = this.matricesIndices;
  36516. serializationObject.matricesIndices._isExpanded = true;
  36517. }
  36518. if (this.matricesWeights) {
  36519. serializationObject.matricesWeights = this.matricesWeights;
  36520. }
  36521. if (this.matricesIndicesExtra) {
  36522. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36523. serializationObject.matricesIndicesExtra._isExpanded = true;
  36524. }
  36525. if (this.matricesWeightsExtra) {
  36526. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36527. }
  36528. serializationObject.indices = this.indices;
  36529. return serializationObject;
  36530. };
  36531. // Statics
  36532. /**
  36533. * Extracts the vertexData from a mesh
  36534. * @param mesh the mesh from which to extract the VertexData
  36535. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36536. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36537. * @returns the object VertexData associated to the passed mesh
  36538. */
  36539. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36540. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36541. };
  36542. /**
  36543. * Extracts the vertexData from the geometry
  36544. * @param geometry the geometry from which to extract the VertexData
  36545. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36546. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36547. * @returns the object VertexData associated to the passed mesh
  36548. */
  36549. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36550. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36551. };
  36552. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36553. var result = new VertexData();
  36554. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36555. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36556. }
  36557. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36558. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36559. }
  36560. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36561. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36562. }
  36563. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36564. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36565. }
  36566. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36567. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36568. }
  36569. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36570. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36571. }
  36572. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36573. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36574. }
  36575. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36576. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36577. }
  36578. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36579. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36580. }
  36581. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36582. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36583. }
  36584. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36585. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36586. }
  36587. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36588. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36589. }
  36590. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36591. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36592. }
  36593. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36594. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36595. }
  36596. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36597. return result;
  36598. };
  36599. /**
  36600. * Creates the VertexData for a Ribbon
  36601. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36602. * * pathArray array of paths, each of which an array of successive Vector3
  36603. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36604. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36605. * * 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
  36606. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36607. * * 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)
  36608. * * 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)
  36609. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36610. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36611. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36612. * @returns the VertexData of the ribbon
  36613. */
  36614. VertexData.CreateRibbon = function (options) {
  36615. var pathArray = options.pathArray;
  36616. var closeArray = options.closeArray || false;
  36617. var closePath = options.closePath || false;
  36618. var invertUV = options.invertUV || false;
  36619. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36620. var offset = options.offset || defaultOffset;
  36621. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36622. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36623. var customUV = options.uvs;
  36624. var customColors = options.colors;
  36625. var positions = [];
  36626. var indices = [];
  36627. var normals = [];
  36628. var uvs = [];
  36629. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36630. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36631. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36632. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36633. var minlg; // minimal length among all paths from pathArray
  36634. var lg = []; // array of path lengths : nb of vertex per path
  36635. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36636. var p; // path iterator
  36637. var i; // point iterator
  36638. var j; // point iterator
  36639. // if single path in pathArray
  36640. if (pathArray.length < 2) {
  36641. var ar1 = [];
  36642. var ar2 = [];
  36643. for (i = 0; i < pathArray[0].length - offset; i++) {
  36644. ar1.push(pathArray[0][i]);
  36645. ar2.push(pathArray[0][i + offset]);
  36646. }
  36647. pathArray = [ar1, ar2];
  36648. }
  36649. // positions and horizontal distances (u)
  36650. var idc = 0;
  36651. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36652. var path;
  36653. var l;
  36654. minlg = pathArray[0].length;
  36655. var vectlg;
  36656. var dist;
  36657. for (p = 0; p < pathArray.length; p++) {
  36658. uTotalDistance[p] = 0;
  36659. us[p] = [0];
  36660. path = pathArray[p];
  36661. l = path.length;
  36662. minlg = (minlg < l) ? minlg : l;
  36663. j = 0;
  36664. while (j < l) {
  36665. positions.push(path[j].x, path[j].y, path[j].z);
  36666. if (j > 0) {
  36667. vectlg = path[j].subtract(path[j - 1]).length();
  36668. dist = vectlg + uTotalDistance[p];
  36669. us[p].push(dist);
  36670. uTotalDistance[p] = dist;
  36671. }
  36672. j++;
  36673. }
  36674. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36675. j--;
  36676. positions.push(path[0].x, path[0].y, path[0].z);
  36677. vectlg = path[j].subtract(path[0]).length();
  36678. dist = vectlg + uTotalDistance[p];
  36679. us[p].push(dist);
  36680. uTotalDistance[p] = dist;
  36681. }
  36682. lg[p] = l + closePathCorr;
  36683. idx[p] = idc;
  36684. idc += (l + closePathCorr);
  36685. }
  36686. // vertical distances (v)
  36687. var path1;
  36688. var path2;
  36689. var vertex1 = null;
  36690. var vertex2 = null;
  36691. for (i = 0; i < minlg + closePathCorr; i++) {
  36692. vTotalDistance[i] = 0;
  36693. vs[i] = [0];
  36694. for (p = 0; p < pathArray.length - 1; p++) {
  36695. path1 = pathArray[p];
  36696. path2 = pathArray[p + 1];
  36697. if (i === minlg) { // closePath
  36698. vertex1 = path1[0];
  36699. vertex2 = path2[0];
  36700. }
  36701. else {
  36702. vertex1 = path1[i];
  36703. vertex2 = path2[i];
  36704. }
  36705. vectlg = vertex2.subtract(vertex1).length();
  36706. dist = vectlg + vTotalDistance[i];
  36707. vs[i].push(dist);
  36708. vTotalDistance[i] = dist;
  36709. }
  36710. if (closeArray && vertex2 && vertex1) {
  36711. path1 = pathArray[p];
  36712. path2 = pathArray[0];
  36713. if (i === minlg) { // closePath
  36714. vertex2 = path2[0];
  36715. }
  36716. vectlg = vertex2.subtract(vertex1).length();
  36717. dist = vectlg + vTotalDistance[i];
  36718. vTotalDistance[i] = dist;
  36719. }
  36720. }
  36721. // uvs
  36722. var u;
  36723. var v;
  36724. if (customUV) {
  36725. for (p = 0; p < customUV.length; p++) {
  36726. uvs.push(customUV[p].x, customUV[p].y);
  36727. }
  36728. }
  36729. else {
  36730. for (p = 0; p < pathArray.length; p++) {
  36731. for (i = 0; i < minlg + closePathCorr; i++) {
  36732. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36733. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36734. if (invertUV) {
  36735. uvs.push(v, u);
  36736. }
  36737. else {
  36738. uvs.push(u, v);
  36739. }
  36740. }
  36741. }
  36742. }
  36743. // indices
  36744. p = 0; // path index
  36745. var pi = 0; // positions array index
  36746. var l1 = lg[p] - 1; // path1 length
  36747. var l2 = lg[p + 1] - 1; // path2 length
  36748. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36749. var shft = idx[1] - idx[0]; // shift
  36750. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36751. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36752. // 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
  36753. indices.push(pi, pi + shft, pi + 1);
  36754. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36755. pi += 1;
  36756. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36757. p++;
  36758. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36759. shft = idx[0] - idx[p];
  36760. l1 = lg[p] - 1;
  36761. l2 = lg[0] - 1;
  36762. }
  36763. else {
  36764. shft = idx[p + 1] - idx[p];
  36765. l1 = lg[p] - 1;
  36766. l2 = lg[p + 1] - 1;
  36767. }
  36768. pi = idx[p];
  36769. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36770. }
  36771. }
  36772. // normals
  36773. VertexData.ComputeNormals(positions, indices, normals);
  36774. if (closePath) { // update both the first and last vertex normals to their average value
  36775. var indexFirst = 0;
  36776. var indexLast = 0;
  36777. for (p = 0; p < pathArray.length; p++) {
  36778. indexFirst = idx[p] * 3;
  36779. if (p + 1 < pathArray.length) {
  36780. indexLast = (idx[p + 1] - 1) * 3;
  36781. }
  36782. else {
  36783. indexLast = normals.length - 3;
  36784. }
  36785. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36786. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36787. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36788. normals[indexLast] = normals[indexFirst];
  36789. normals[indexLast + 1] = normals[indexFirst + 1];
  36790. normals[indexLast + 2] = normals[indexFirst + 2];
  36791. }
  36792. }
  36793. // sides
  36794. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36795. // Colors
  36796. var colors = null;
  36797. if (customColors) {
  36798. colors = new Float32Array(customColors.length * 4);
  36799. for (var c = 0; c < customColors.length; c++) {
  36800. colors[c * 4] = customColors[c].r;
  36801. colors[c * 4 + 1] = customColors[c].g;
  36802. colors[c * 4 + 2] = customColors[c].b;
  36803. colors[c * 4 + 3] = customColors[c].a;
  36804. }
  36805. }
  36806. // Result
  36807. var vertexData = new VertexData();
  36808. var positions32 = new Float32Array(positions);
  36809. var normals32 = new Float32Array(normals);
  36810. var uvs32 = new Float32Array(uvs);
  36811. vertexData.indices = indices;
  36812. vertexData.positions = positions32;
  36813. vertexData.normals = normals32;
  36814. vertexData.uvs = uvs32;
  36815. if (colors) {
  36816. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36817. }
  36818. if (closePath) {
  36819. vertexData._idx = idx;
  36820. }
  36821. return vertexData;
  36822. };
  36823. /**
  36824. * Creates the VertexData for a box
  36825. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36826. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36827. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36828. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36829. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36830. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36831. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36832. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36833. * * 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)
  36834. * * 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)
  36835. * @returns the VertexData of the box
  36836. */
  36837. VertexData.CreateBox = function (options) {
  36838. var normalsSource = [
  36839. new BABYLON.Vector3(0, 0, 1),
  36840. new BABYLON.Vector3(0, 0, -1),
  36841. new BABYLON.Vector3(1, 0, 0),
  36842. new BABYLON.Vector3(-1, 0, 0),
  36843. new BABYLON.Vector3(0, 1, 0),
  36844. new BABYLON.Vector3(0, -1, 0)
  36845. ];
  36846. var indices = [];
  36847. var positions = [];
  36848. var normals = [];
  36849. var uvs = [];
  36850. var width = options.width || options.size || 1;
  36851. var height = options.height || options.size || 1;
  36852. var depth = options.depth || options.size || 1;
  36853. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36854. var faceUV = options.faceUV || new Array(6);
  36855. var faceColors = options.faceColors;
  36856. var colors = [];
  36857. // default face colors and UV if undefined
  36858. for (var f = 0; f < 6; f++) {
  36859. if (faceUV[f] === undefined) {
  36860. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36861. }
  36862. if (faceColors && faceColors[f] === undefined) {
  36863. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36864. }
  36865. }
  36866. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36867. // Create each face in turn.
  36868. for (var index = 0; index < normalsSource.length; index++) {
  36869. var normal = normalsSource[index];
  36870. // Get two vectors perpendicular to the face normal and to each other.
  36871. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36872. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36873. // Six indices (two triangles) per face.
  36874. var verticesLength = positions.length / 3;
  36875. indices.push(verticesLength);
  36876. indices.push(verticesLength + 1);
  36877. indices.push(verticesLength + 2);
  36878. indices.push(verticesLength);
  36879. indices.push(verticesLength + 2);
  36880. indices.push(verticesLength + 3);
  36881. // Four vertices per face.
  36882. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36883. positions.push(vertex.x, vertex.y, vertex.z);
  36884. normals.push(normal.x, normal.y, normal.z);
  36885. uvs.push(faceUV[index].z, faceUV[index].w);
  36886. if (faceColors) {
  36887. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36888. }
  36889. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36890. positions.push(vertex.x, vertex.y, vertex.z);
  36891. normals.push(normal.x, normal.y, normal.z);
  36892. uvs.push(faceUV[index].x, faceUV[index].w);
  36893. if (faceColors) {
  36894. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36895. }
  36896. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36897. positions.push(vertex.x, vertex.y, vertex.z);
  36898. normals.push(normal.x, normal.y, normal.z);
  36899. uvs.push(faceUV[index].x, faceUV[index].y);
  36900. if (faceColors) {
  36901. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36902. }
  36903. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36904. positions.push(vertex.x, vertex.y, vertex.z);
  36905. normals.push(normal.x, normal.y, normal.z);
  36906. uvs.push(faceUV[index].z, faceUV[index].y);
  36907. if (faceColors) {
  36908. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36909. }
  36910. }
  36911. // sides
  36912. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36913. // Result
  36914. var vertexData = new VertexData();
  36915. vertexData.indices = indices;
  36916. vertexData.positions = positions;
  36917. vertexData.normals = normals;
  36918. vertexData.uvs = uvs;
  36919. if (faceColors) {
  36920. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36921. vertexData.colors = totalColors;
  36922. }
  36923. return vertexData;
  36924. };
  36925. /**
  36926. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36927. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36928. * * segments sets the number of horizontal strips optional, default 32
  36929. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36930. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36931. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36932. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36933. * * 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
  36934. * * 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
  36935. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36936. * * 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)
  36937. * * 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)
  36938. * @returns the VertexData of the ellipsoid
  36939. */
  36940. VertexData.CreateSphere = function (options) {
  36941. var segments = options.segments || 32;
  36942. var diameterX = options.diameterX || options.diameter || 1;
  36943. var diameterY = options.diameterY || options.diameter || 1;
  36944. var diameterZ = options.diameterZ || options.diameter || 1;
  36945. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36946. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36947. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36948. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36949. var totalZRotationSteps = 2 + segments;
  36950. var totalYRotationSteps = 2 * totalZRotationSteps;
  36951. var indices = [];
  36952. var positions = [];
  36953. var normals = [];
  36954. var uvs = [];
  36955. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36956. var normalizedZ = zRotationStep / totalZRotationSteps;
  36957. var angleZ = normalizedZ * Math.PI * slice;
  36958. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36959. var normalizedY = yRotationStep / totalYRotationSteps;
  36960. var angleY = normalizedY * Math.PI * 2 * arc;
  36961. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36962. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36963. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36964. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36965. var vertex = complete.multiply(radius);
  36966. var normal = complete.divide(radius).normalize();
  36967. positions.push(vertex.x, vertex.y, vertex.z);
  36968. normals.push(normal.x, normal.y, normal.z);
  36969. uvs.push(normalizedY, normalizedZ);
  36970. }
  36971. if (zRotationStep > 0) {
  36972. var verticesCount = positions.length / 3;
  36973. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36974. indices.push((firstIndex));
  36975. indices.push((firstIndex + 1));
  36976. indices.push(firstIndex + totalYRotationSteps + 1);
  36977. indices.push((firstIndex + totalYRotationSteps + 1));
  36978. indices.push((firstIndex + 1));
  36979. indices.push((firstIndex + totalYRotationSteps + 2));
  36980. }
  36981. }
  36982. }
  36983. // Sides
  36984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36985. // Result
  36986. var vertexData = new VertexData();
  36987. vertexData.indices = indices;
  36988. vertexData.positions = positions;
  36989. vertexData.normals = normals;
  36990. vertexData.uvs = uvs;
  36991. return vertexData;
  36992. };
  36993. /**
  36994. * Creates the VertexData for a cylinder, cone or prism
  36995. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36996. * * height sets the height (y direction) of the cylinder, optional, default 2
  36997. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36998. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36999. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37000. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37001. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37002. * * 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
  37003. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37004. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37005. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37006. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37007. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37008. * * 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)
  37009. * * 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)
  37010. * @returns the VertexData of the cylinder, cone or prism
  37011. */
  37012. VertexData.CreateCylinder = function (options) {
  37013. var height = options.height || 2;
  37014. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37015. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37016. var tessellation = options.tessellation || 24;
  37017. var subdivisions = options.subdivisions || 1;
  37018. var hasRings = options.hasRings ? true : false;
  37019. var enclose = options.enclose ? true : false;
  37020. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37022. var faceUV = options.faceUV || new Array(3);
  37023. var faceColors = options.faceColors;
  37024. // default face colors and UV if undefined
  37025. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37026. var ringNb = (hasRings) ? subdivisions : 1;
  37027. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37028. var f;
  37029. for (f = 0; f < surfaceNb; f++) {
  37030. if (faceColors && faceColors[f] === undefined) {
  37031. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37032. }
  37033. }
  37034. for (f = 0; f < surfaceNb; f++) {
  37035. if (faceUV && faceUV[f] === undefined) {
  37036. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37037. }
  37038. }
  37039. var indices = new Array();
  37040. var positions = new Array();
  37041. var normals = new Array();
  37042. var uvs = new Array();
  37043. var colors = new Array();
  37044. var angle_step = Math.PI * 2 * arc / tessellation;
  37045. var angle;
  37046. var h;
  37047. var radius;
  37048. var tan = (diameterBottom - diameterTop) / 2 / height;
  37049. var ringVertex = BABYLON.Vector3.Zero();
  37050. var ringNormal = BABYLON.Vector3.Zero();
  37051. var ringFirstVertex = BABYLON.Vector3.Zero();
  37052. var ringFirstNormal = BABYLON.Vector3.Zero();
  37053. var quadNormal = BABYLON.Vector3.Zero();
  37054. var Y = BABYLON.Axis.Y;
  37055. // positions, normals, uvs
  37056. var i;
  37057. var j;
  37058. var r;
  37059. var ringIdx = 1;
  37060. var s = 1; // surface index
  37061. var cs = 0;
  37062. var v = 0;
  37063. for (i = 0; i <= subdivisions; i++) {
  37064. h = i / subdivisions;
  37065. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37066. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37067. for (r = 0; r < ringIdx; r++) {
  37068. if (hasRings) {
  37069. s += r;
  37070. }
  37071. if (enclose) {
  37072. s += 2 * r;
  37073. }
  37074. for (j = 0; j <= tessellation; j++) {
  37075. angle = j * angle_step;
  37076. // position
  37077. ringVertex.x = Math.cos(-angle) * radius;
  37078. ringVertex.y = -height / 2 + h * height;
  37079. ringVertex.z = Math.sin(-angle) * radius;
  37080. // normal
  37081. if (diameterTop === 0 && i === subdivisions) {
  37082. // if no top cap, reuse former normals
  37083. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37084. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37085. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37086. }
  37087. else {
  37088. ringNormal.x = ringVertex.x;
  37089. ringNormal.z = ringVertex.z;
  37090. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37091. ringNormal.normalize();
  37092. }
  37093. // keep first ring vertex values for enclose
  37094. if (j === 0) {
  37095. ringFirstVertex.copyFrom(ringVertex);
  37096. ringFirstNormal.copyFrom(ringNormal);
  37097. }
  37098. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37099. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37100. if (hasRings) {
  37101. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37102. }
  37103. else {
  37104. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37105. }
  37106. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37107. if (faceColors) {
  37108. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37109. }
  37110. }
  37111. // if enclose, add four vertices and their dedicated normals
  37112. if (arc !== 1 && enclose) {
  37113. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37114. positions.push(0, ringVertex.y, 0);
  37115. positions.push(0, ringVertex.y, 0);
  37116. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37117. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37118. quadNormal.normalize();
  37119. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37120. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37121. quadNormal.normalize();
  37122. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37123. if (hasRings) {
  37124. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37125. }
  37126. else {
  37127. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37128. }
  37129. uvs.push(faceUV[s + 1].x, v);
  37130. uvs.push(faceUV[s + 1].z, v);
  37131. if (hasRings) {
  37132. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37133. }
  37134. else {
  37135. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37136. }
  37137. uvs.push(faceUV[s + 2].x, v);
  37138. uvs.push(faceUV[s + 2].z, v);
  37139. if (faceColors) {
  37140. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37141. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37142. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37143. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37144. }
  37145. }
  37146. if (cs !== s) {
  37147. cs = s;
  37148. }
  37149. }
  37150. }
  37151. // indices
  37152. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37153. var s;
  37154. i = 0;
  37155. for (s = 0; s < subdivisions; s++) {
  37156. var i0 = 0;
  37157. var i1 = 0;
  37158. var i2 = 0;
  37159. var i3 = 0;
  37160. for (j = 0; j < tessellation; j++) {
  37161. i0 = i * (e + 1) + j;
  37162. i1 = (i + 1) * (e + 1) + j;
  37163. i2 = i * (e + 1) + (j + 1);
  37164. i3 = (i + 1) * (e + 1) + (j + 1);
  37165. indices.push(i0, i1, i2);
  37166. indices.push(i3, i2, i1);
  37167. }
  37168. if (arc !== 1 && enclose) { // if enclose, add two quads
  37169. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37170. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37171. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37172. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37173. }
  37174. i = (hasRings) ? (i + 2) : (i + 1);
  37175. }
  37176. // Caps
  37177. var createCylinderCap = function (isTop) {
  37178. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37179. if (radius === 0) {
  37180. return;
  37181. }
  37182. // Cap positions, normals & uvs
  37183. var angle;
  37184. var circleVector;
  37185. var i;
  37186. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37187. var c = null;
  37188. if (faceColors) {
  37189. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37190. }
  37191. // cap center
  37192. var vbase = positions.length / 3;
  37193. var offset = isTop ? height / 2 : -height / 2;
  37194. var center = new BABYLON.Vector3(0, offset, 0);
  37195. positions.push(center.x, center.y, center.z);
  37196. normals.push(0, isTop ? 1 : -1, 0);
  37197. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37198. if (c) {
  37199. colors.push(c.r, c.g, c.b, c.a);
  37200. }
  37201. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37202. for (i = 0; i <= tessellation; i++) {
  37203. angle = Math.PI * 2 * i * arc / tessellation;
  37204. var cos = Math.cos(-angle);
  37205. var sin = Math.sin(-angle);
  37206. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37207. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37208. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37209. normals.push(0, isTop ? 1 : -1, 0);
  37210. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37211. if (c) {
  37212. colors.push(c.r, c.g, c.b, c.a);
  37213. }
  37214. }
  37215. // Cap indices
  37216. for (i = 0; i < tessellation; i++) {
  37217. if (!isTop) {
  37218. indices.push(vbase);
  37219. indices.push(vbase + (i + 1));
  37220. indices.push(vbase + (i + 2));
  37221. }
  37222. else {
  37223. indices.push(vbase);
  37224. indices.push(vbase + (i + 2));
  37225. indices.push(vbase + (i + 1));
  37226. }
  37227. }
  37228. };
  37229. // add caps to geometry
  37230. createCylinderCap(false);
  37231. createCylinderCap(true);
  37232. // Sides
  37233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37234. var vertexData = new VertexData();
  37235. vertexData.indices = indices;
  37236. vertexData.positions = positions;
  37237. vertexData.normals = normals;
  37238. vertexData.uvs = uvs;
  37239. if (faceColors) {
  37240. vertexData.colors = colors;
  37241. }
  37242. return vertexData;
  37243. };
  37244. /**
  37245. * Creates the VertexData for a torus
  37246. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37247. * * diameter the diameter of the torus, optional default 1
  37248. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37249. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37250. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37251. * * 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)
  37252. * * 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)
  37253. * @returns the VertexData of the torus
  37254. */
  37255. VertexData.CreateTorus = function (options) {
  37256. var indices = [];
  37257. var positions = [];
  37258. var normals = [];
  37259. var uvs = [];
  37260. var diameter = options.diameter || 1;
  37261. var thickness = options.thickness || 0.5;
  37262. var tessellation = options.tessellation || 16;
  37263. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37264. var stride = tessellation + 1;
  37265. for (var i = 0; i <= tessellation; i++) {
  37266. var u = i / tessellation;
  37267. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37268. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37269. for (var j = 0; j <= tessellation; j++) {
  37270. var v = 1 - j / tessellation;
  37271. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37272. var dx = Math.cos(innerAngle);
  37273. var dy = Math.sin(innerAngle);
  37274. // Create a vertex.
  37275. var normal = new BABYLON.Vector3(dx, dy, 0);
  37276. var position = normal.scale(thickness / 2);
  37277. var textureCoordinate = new BABYLON.Vector2(u, v);
  37278. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37279. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37280. positions.push(position.x, position.y, position.z);
  37281. normals.push(normal.x, normal.y, normal.z);
  37282. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37283. // And create indices for two triangles.
  37284. var nextI = (i + 1) % stride;
  37285. var nextJ = (j + 1) % stride;
  37286. indices.push(i * stride + j);
  37287. indices.push(i * stride + nextJ);
  37288. indices.push(nextI * stride + j);
  37289. indices.push(i * stride + nextJ);
  37290. indices.push(nextI * stride + nextJ);
  37291. indices.push(nextI * stride + j);
  37292. }
  37293. }
  37294. // Sides
  37295. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37296. // Result
  37297. var vertexData = new VertexData();
  37298. vertexData.indices = indices;
  37299. vertexData.positions = positions;
  37300. vertexData.normals = normals;
  37301. vertexData.uvs = uvs;
  37302. return vertexData;
  37303. };
  37304. /**
  37305. * Creates the VertexData of the LineSystem
  37306. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37307. * - lines an array of lines, each line being an array of successive Vector3
  37308. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37309. * @returns the VertexData of the LineSystem
  37310. */
  37311. VertexData.CreateLineSystem = function (options) {
  37312. var indices = [];
  37313. var positions = [];
  37314. var lines = options.lines;
  37315. var colors = options.colors;
  37316. var vertexColors = [];
  37317. var idx = 0;
  37318. for (var l = 0; l < lines.length; l++) {
  37319. var points = lines[l];
  37320. for (var index = 0; index < points.length; index++) {
  37321. positions.push(points[index].x, points[index].y, points[index].z);
  37322. if (colors) {
  37323. var color = colors[l];
  37324. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37325. }
  37326. if (index > 0) {
  37327. indices.push(idx - 1);
  37328. indices.push(idx);
  37329. }
  37330. idx++;
  37331. }
  37332. }
  37333. var vertexData = new VertexData();
  37334. vertexData.indices = indices;
  37335. vertexData.positions = positions;
  37336. if (colors) {
  37337. vertexData.colors = vertexColors;
  37338. }
  37339. return vertexData;
  37340. };
  37341. /**
  37342. * Create the VertexData for a DashedLines
  37343. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37344. * - points an array successive Vector3
  37345. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37346. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37347. * - dashNb the intended total number of dashes, optional, default 200
  37348. * @returns the VertexData for the DashedLines
  37349. */
  37350. VertexData.CreateDashedLines = function (options) {
  37351. var dashSize = options.dashSize || 3;
  37352. var gapSize = options.gapSize || 1;
  37353. var dashNb = options.dashNb || 200;
  37354. var points = options.points;
  37355. var positions = new Array();
  37356. var indices = new Array();
  37357. var curvect = BABYLON.Vector3.Zero();
  37358. var lg = 0;
  37359. var nb = 0;
  37360. var shft = 0;
  37361. var dashshft = 0;
  37362. var curshft = 0;
  37363. var idx = 0;
  37364. var i = 0;
  37365. for (i = 0; i < points.length - 1; i++) {
  37366. points[i + 1].subtractToRef(points[i], curvect);
  37367. lg += curvect.length();
  37368. }
  37369. shft = lg / dashNb;
  37370. dashshft = dashSize * shft / (dashSize + gapSize);
  37371. for (i = 0; i < points.length - 1; i++) {
  37372. points[i + 1].subtractToRef(points[i], curvect);
  37373. nb = Math.floor(curvect.length() / shft);
  37374. curvect.normalize();
  37375. for (var j = 0; j < nb; j++) {
  37376. curshft = shft * j;
  37377. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37378. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37379. indices.push(idx, idx + 1);
  37380. idx += 2;
  37381. }
  37382. }
  37383. // Result
  37384. var vertexData = new VertexData();
  37385. vertexData.positions = positions;
  37386. vertexData.indices = indices;
  37387. return vertexData;
  37388. };
  37389. /**
  37390. * Creates the VertexData for a Ground
  37391. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37392. * - width the width (x direction) of the ground, optional, default 1
  37393. * - height the height (z direction) of the ground, optional, default 1
  37394. * - subdivisions the number of subdivisions per side, optional, default 1
  37395. * @returns the VertexData of the Ground
  37396. */
  37397. VertexData.CreateGround = function (options) {
  37398. var indices = [];
  37399. var positions = [];
  37400. var normals = [];
  37401. var uvs = [];
  37402. var row, col;
  37403. var width = options.width || 1;
  37404. var height = options.height || 1;
  37405. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37406. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37407. for (row = 0; row <= subdivisionsY; row++) {
  37408. for (col = 0; col <= subdivisionsX; col++) {
  37409. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37410. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37411. positions.push(position.x, position.y, position.z);
  37412. normals.push(normal.x, normal.y, normal.z);
  37413. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37414. }
  37415. }
  37416. for (row = 0; row < subdivisionsY; row++) {
  37417. for (col = 0; col < subdivisionsX; col++) {
  37418. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37419. indices.push(col + 1 + row * (subdivisionsX + 1));
  37420. indices.push(col + row * (subdivisionsX + 1));
  37421. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37422. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37423. indices.push(col + row * (subdivisionsX + 1));
  37424. }
  37425. }
  37426. // Result
  37427. var vertexData = new VertexData();
  37428. vertexData.indices = indices;
  37429. vertexData.positions = positions;
  37430. vertexData.normals = normals;
  37431. vertexData.uvs = uvs;
  37432. return vertexData;
  37433. };
  37434. /**
  37435. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37436. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37437. * * xmin the ground minimum X coordinate, optional, default -1
  37438. * * zmin the ground minimum Z coordinate, optional, default -1
  37439. * * xmax the ground maximum X coordinate, optional, default 1
  37440. * * zmax the ground maximum Z coordinate, optional, default 1
  37441. * * 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}
  37442. * * 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}
  37443. * @returns the VertexData of the TiledGround
  37444. */
  37445. VertexData.CreateTiledGround = function (options) {
  37446. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37447. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37448. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37449. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37450. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37451. var precision = options.precision || { w: 1, h: 1 };
  37452. var indices = new Array();
  37453. var positions = new Array();
  37454. var normals = new Array();
  37455. var uvs = new Array();
  37456. var row, col, tileRow, tileCol;
  37457. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37458. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37459. precision.w = (precision.w < 1) ? 1 : precision.w;
  37460. precision.h = (precision.h < 1) ? 1 : precision.h;
  37461. var tileSize = {
  37462. 'w': (xmax - xmin) / subdivisions.w,
  37463. 'h': (zmax - zmin) / subdivisions.h
  37464. };
  37465. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37466. // Indices
  37467. var base = positions.length / 3;
  37468. var rowLength = precision.w + 1;
  37469. for (row = 0; row < precision.h; row++) {
  37470. for (col = 0; col < precision.w; col++) {
  37471. var square = [
  37472. base + col + row * rowLength,
  37473. base + (col + 1) + row * rowLength,
  37474. base + (col + 1) + (row + 1) * rowLength,
  37475. base + col + (row + 1) * rowLength
  37476. ];
  37477. indices.push(square[1]);
  37478. indices.push(square[2]);
  37479. indices.push(square[3]);
  37480. indices.push(square[0]);
  37481. indices.push(square[1]);
  37482. indices.push(square[3]);
  37483. }
  37484. }
  37485. // Position, normals and uvs
  37486. var position = BABYLON.Vector3.Zero();
  37487. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37488. for (row = 0; row <= precision.h; row++) {
  37489. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37490. for (col = 0; col <= precision.w; col++) {
  37491. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37492. position.y = 0;
  37493. positions.push(position.x, position.y, position.z);
  37494. normals.push(normal.x, normal.y, normal.z);
  37495. uvs.push(col / precision.w, row / precision.h);
  37496. }
  37497. }
  37498. }
  37499. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37500. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37501. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37502. }
  37503. }
  37504. // Result
  37505. var vertexData = new VertexData();
  37506. vertexData.indices = indices;
  37507. vertexData.positions = positions;
  37508. vertexData.normals = normals;
  37509. vertexData.uvs = uvs;
  37510. return vertexData;
  37511. };
  37512. /**
  37513. * Creates the VertexData of the Ground designed from a heightmap
  37514. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37515. * * width the width (x direction) of the ground
  37516. * * height the height (z direction) of the ground
  37517. * * subdivisions the number of subdivisions per side
  37518. * * minHeight the minimum altitude on the ground, optional, default 0
  37519. * * maxHeight the maximum altitude on the ground, optional default 1
  37520. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37521. * * buffer the array holding the image color data
  37522. * * bufferWidth the width of image
  37523. * * bufferHeight the height of image
  37524. * @returns the VertexData of the Ground designed from a heightmap
  37525. */
  37526. VertexData.CreateGroundFromHeightMap = function (options) {
  37527. var indices = [];
  37528. var positions = [];
  37529. var normals = [];
  37530. var uvs = [];
  37531. var row, col;
  37532. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37533. // Vertices
  37534. for (row = 0; row <= options.subdivisions; row++) {
  37535. for (col = 0; col <= options.subdivisions; col++) {
  37536. 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));
  37537. // Compute height
  37538. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37539. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37540. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37541. var r = options.buffer[pos] / 255.0;
  37542. var g = options.buffer[pos + 1] / 255.0;
  37543. var b = options.buffer[pos + 2] / 255.0;
  37544. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37545. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37546. // Add vertex
  37547. positions.push(position.x, position.y, position.z);
  37548. normals.push(0, 0, 0);
  37549. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37550. }
  37551. }
  37552. // Indices
  37553. for (row = 0; row < options.subdivisions; row++) {
  37554. for (col = 0; col < options.subdivisions; col++) {
  37555. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37556. indices.push(col + 1 + row * (options.subdivisions + 1));
  37557. indices.push(col + row * (options.subdivisions + 1));
  37558. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37559. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37560. indices.push(col + row * (options.subdivisions + 1));
  37561. }
  37562. }
  37563. // Normals
  37564. VertexData.ComputeNormals(positions, indices, normals);
  37565. // Result
  37566. var vertexData = new VertexData();
  37567. vertexData.indices = indices;
  37568. vertexData.positions = positions;
  37569. vertexData.normals = normals;
  37570. vertexData.uvs = uvs;
  37571. return vertexData;
  37572. };
  37573. /**
  37574. * Creates the VertexData for a Plane
  37575. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37576. * * size sets the width and height of the plane to the value of size, optional default 1
  37577. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37578. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37579. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37580. * * 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)
  37581. * * 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)
  37582. * @returns the VertexData of the box
  37583. */
  37584. VertexData.CreatePlane = function (options) {
  37585. var indices = [];
  37586. var positions = [];
  37587. var normals = [];
  37588. var uvs = [];
  37589. var width = options.width || options.size || 1;
  37590. var height = options.height || options.size || 1;
  37591. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37592. // Vertices
  37593. var halfWidth = width / 2.0;
  37594. var halfHeight = height / 2.0;
  37595. positions.push(-halfWidth, -halfHeight, 0);
  37596. normals.push(0, 0, -1.0);
  37597. uvs.push(0.0, 0.0);
  37598. positions.push(halfWidth, -halfHeight, 0);
  37599. normals.push(0, 0, -1.0);
  37600. uvs.push(1.0, 0.0);
  37601. positions.push(halfWidth, halfHeight, 0);
  37602. normals.push(0, 0, -1.0);
  37603. uvs.push(1.0, 1.0);
  37604. positions.push(-halfWidth, halfHeight, 0);
  37605. normals.push(0, 0, -1.0);
  37606. uvs.push(0.0, 1.0);
  37607. // Indices
  37608. indices.push(0);
  37609. indices.push(1);
  37610. indices.push(2);
  37611. indices.push(0);
  37612. indices.push(2);
  37613. indices.push(3);
  37614. // Sides
  37615. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37616. // Result
  37617. var vertexData = new VertexData();
  37618. vertexData.indices = indices;
  37619. vertexData.positions = positions;
  37620. vertexData.normals = normals;
  37621. vertexData.uvs = uvs;
  37622. return vertexData;
  37623. };
  37624. /**
  37625. * Creates the VertexData of the Disc or regular Polygon
  37626. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37627. * * radius the radius of the disc, optional default 0.5
  37628. * * tessellation the number of polygon sides, optional, default 64
  37629. * * 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
  37630. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37631. * * 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)
  37632. * * 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)
  37633. * @returns the VertexData of the box
  37634. */
  37635. VertexData.CreateDisc = function (options) {
  37636. var positions = new Array();
  37637. var indices = new Array();
  37638. var normals = new Array();
  37639. var uvs = new Array();
  37640. var radius = options.radius || 0.5;
  37641. var tessellation = options.tessellation || 64;
  37642. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37644. // positions and uvs
  37645. positions.push(0, 0, 0); // disc center first
  37646. uvs.push(0.5, 0.5);
  37647. var theta = Math.PI * 2 * arc;
  37648. var step = theta / tessellation;
  37649. for (var a = 0; a < theta; a += step) {
  37650. var x = Math.cos(a);
  37651. var y = Math.sin(a);
  37652. var u = (x + 1) / 2;
  37653. var v = (1 - y) / 2;
  37654. positions.push(radius * x, radius * y, 0);
  37655. uvs.push(u, v);
  37656. }
  37657. if (arc === 1) {
  37658. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37659. uvs.push(uvs[2], uvs[3]);
  37660. }
  37661. //indices
  37662. var vertexNb = positions.length / 3;
  37663. for (var i = 1; i < vertexNb - 1; i++) {
  37664. indices.push(i + 1, 0, i);
  37665. }
  37666. // result
  37667. VertexData.ComputeNormals(positions, indices, normals);
  37668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37669. var vertexData = new VertexData();
  37670. vertexData.indices = indices;
  37671. vertexData.positions = positions;
  37672. vertexData.normals = normals;
  37673. vertexData.uvs = uvs;
  37674. return vertexData;
  37675. };
  37676. /**
  37677. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37678. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37679. * @param polygon a mesh built from polygonTriangulation.build()
  37680. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37681. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37682. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37683. * @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)
  37684. * @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)
  37685. * @returns the VertexData of the Polygon
  37686. */
  37687. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37688. var faceUV = fUV || new Array(3);
  37689. var faceColors = fColors;
  37690. var colors = [];
  37691. // default face colors and UV if undefined
  37692. for (var f = 0; f < 3; f++) {
  37693. if (faceUV[f] === undefined) {
  37694. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37695. }
  37696. if (faceColors && faceColors[f] === undefined) {
  37697. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37698. }
  37699. }
  37700. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37701. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37702. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37703. var indices = polygon.getIndices();
  37704. // set face colours and textures
  37705. var idx = 0;
  37706. var face = 0;
  37707. for (var index = 0; index < normals.length; index += 3) {
  37708. //Edge Face no. 1
  37709. if (Math.abs(normals[index + 1]) < 0.001) {
  37710. face = 1;
  37711. }
  37712. //Top Face no. 0
  37713. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37714. face = 0;
  37715. }
  37716. //Bottom Face no. 2
  37717. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37718. face = 2;
  37719. }
  37720. idx = index / 3;
  37721. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37722. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37723. if (faceColors) {
  37724. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37725. }
  37726. }
  37727. // sides
  37728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37729. // Result
  37730. var vertexData = new VertexData();
  37731. vertexData.indices = indices;
  37732. vertexData.positions = positions;
  37733. vertexData.normals = normals;
  37734. vertexData.uvs = uvs;
  37735. if (faceColors) {
  37736. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37737. vertexData.colors = totalColors;
  37738. }
  37739. return vertexData;
  37740. };
  37741. /**
  37742. * Creates the VertexData of the IcoSphere
  37743. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37744. * * radius the radius of the IcoSphere, optional default 1
  37745. * * radiusX allows stretching in the x direction, optional, default radius
  37746. * * radiusY allows stretching in the y direction, optional, default radius
  37747. * * radiusZ allows stretching in the z direction, optional, default radius
  37748. * * flat when true creates a flat shaded mesh, optional, default true
  37749. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37750. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37751. * * 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)
  37752. * * 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)
  37753. * @returns the VertexData of the IcoSphere
  37754. */
  37755. VertexData.CreateIcoSphere = function (options) {
  37756. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37757. var radius = options.radius || 1;
  37758. var flat = (options.flat === undefined) ? true : options.flat;
  37759. var subdivisions = options.subdivisions || 4;
  37760. var radiusX = options.radiusX || radius;
  37761. var radiusY = options.radiusY || radius;
  37762. var radiusZ = options.radiusZ || radius;
  37763. var t = (1 + Math.sqrt(5)) / 2;
  37764. // 12 vertex x,y,z
  37765. var ico_vertices = [
  37766. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37767. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37768. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37769. ];
  37770. // index of 3 vertex makes a face of icopshere
  37771. var ico_indices = [
  37772. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37773. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37774. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37775. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37776. ];
  37777. // vertex for uv have aliased position, not for UV
  37778. var vertices_unalias_id = [
  37779. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37780. // vertex alias
  37781. 0,
  37782. 2,
  37783. 3,
  37784. 3,
  37785. 3,
  37786. 4,
  37787. 7,
  37788. 8,
  37789. 9,
  37790. 9,
  37791. 10,
  37792. 11 // 23: B + 12
  37793. ];
  37794. // uv as integer step (not pixels !)
  37795. var ico_vertexuv = [
  37796. 5, 1, 3, 1, 6, 4, 0, 0,
  37797. 5, 3, 4, 2, 2, 2, 4, 0,
  37798. 2, 0, 1, 1, 6, 0, 6, 2,
  37799. // vertex alias (for same vertex on different faces)
  37800. 0, 4,
  37801. 3, 3,
  37802. 4, 4,
  37803. 3, 1,
  37804. 4, 2,
  37805. 4, 4,
  37806. 0, 2,
  37807. 1, 1,
  37808. 2, 2,
  37809. 3, 3,
  37810. 1, 3,
  37811. 2, 4 // 23: B + 12
  37812. ];
  37813. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37814. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37815. // First island of uv mapping
  37816. // v = 4h 3+ 2
  37817. // v = 3h 9+ 4
  37818. // v = 2h 9+ 5 B
  37819. // v = 1h 9 1 0
  37820. // v = 0h 3 8 7 A
  37821. // u = 0 1 2 3 4 5 6 *a
  37822. // Second island of uv mapping
  37823. // v = 4h 0+ B+ 4+
  37824. // v = 3h A+ 2+
  37825. // v = 2h 7+ 6 3+
  37826. // v = 1h 8+ 3+
  37827. // v = 0h
  37828. // u = 0 1 2 3 4 5 6 *a
  37829. // Face layout on texture UV mapping
  37830. // ============
  37831. // \ 4 /\ 16 / ======
  37832. // \ / \ / /\ 11 /
  37833. // \/ 7 \/ / \ /
  37834. // ======= / 10 \/
  37835. // /\ 17 /\ =======
  37836. // / \ / \ \ 15 /\
  37837. // / 8 \/ 12 \ \ / \
  37838. // ============ \/ 6 \
  37839. // \ 18 /\ ============
  37840. // \ / \ \ 5 /\ 0 /
  37841. // \/ 13 \ \ / \ /
  37842. // ======= \/ 1 \/
  37843. // =============
  37844. // /\ 19 /\ 2 /\
  37845. // / \ / \ / \
  37846. // / 14 \/ 9 \/ 3 \
  37847. // ===================
  37848. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37849. var ustep = 138 / 1024;
  37850. var vstep = 239 / 1024;
  37851. var uoffset = 60 / 1024;
  37852. var voffset = 26 / 1024;
  37853. // Second island should have margin, not to touch the first island
  37854. // avoid any borderline artefact in pixel rounding
  37855. var island_u_offset = -40 / 1024;
  37856. var island_v_offset = +20 / 1024;
  37857. // face is either island 0 or 1 :
  37858. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37859. var island = [
  37860. 0, 0, 0, 0, 1,
  37861. 0, 0, 1, 1, 0,
  37862. 0, 0, 1, 1, 0,
  37863. 0, 1, 1, 1, 0 // 15 - 19
  37864. ];
  37865. var indices = new Array();
  37866. var positions = new Array();
  37867. var normals = new Array();
  37868. var uvs = new Array();
  37869. var current_indice = 0;
  37870. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37871. var face_vertex_pos = new Array(3);
  37872. var face_vertex_uv = new Array(3);
  37873. var v012;
  37874. for (v012 = 0; v012 < 3; v012++) {
  37875. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37876. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37877. }
  37878. // create all with normals
  37879. for (var face = 0; face < 20; face++) {
  37880. // 3 vertex per face
  37881. for (v012 = 0; v012 < 3; v012++) {
  37882. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37883. var v_id = ico_indices[3 * face + v012];
  37884. // vertex have 3D position (x,y,z)
  37885. 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]);
  37886. // Normalize to get normal, then scale to radius
  37887. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37888. // uv Coordinates from vertex ID
  37889. 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);
  37890. }
  37891. // Subdivide the face (interpolate pos, norm, uv)
  37892. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37893. // - norm is linear interpolation of vertex corner normal
  37894. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37895. // - uv is linear interpolation
  37896. //
  37897. // Topology is as below for sub-divide by 2
  37898. // vertex shown as v0,v1,v2
  37899. // interp index is i1 to progress in range [v0,v1[
  37900. // interp index is i2 to progress in range [v0,v2[
  37901. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37902. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37903. //
  37904. //
  37905. // i2 v2
  37906. // ^ ^
  37907. // / / \
  37908. // / / \
  37909. // / / \
  37910. // / / (0,1) \
  37911. // / #---------\
  37912. // / / \ (0,0)'/ \
  37913. // / / \ / \
  37914. // / / \ / \
  37915. // / / (0,0) \ / (1,0) \
  37916. // / #---------#---------\
  37917. // v0 v1
  37918. //
  37919. // --------------------> i1
  37920. //
  37921. // interp of (i1,i2):
  37922. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37923. // along i1 : lerp(x0,x1, i1/(S-i2))
  37924. //
  37925. // centroid of triangle is needed to get help normal computation
  37926. // (c1,c2) are used for centroid location
  37927. var interp_vertex = function (i1, i2, c1, c2) {
  37928. // vertex is interpolated from
  37929. // - face_vertex_pos[0..2]
  37930. // - face_vertex_uv[0..2]
  37931. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37932. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37933. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37934. pos_interp.normalize();
  37935. var vertex_normal;
  37936. if (flat) {
  37937. // in flat mode, recalculate normal as face centroid normal
  37938. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37939. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37940. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37941. }
  37942. else {
  37943. // in smooth mode, recalculate normal from each single vertex position
  37944. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37945. }
  37946. // Vertex normal need correction due to X,Y,Z radius scaling
  37947. vertex_normal.x /= radiusX;
  37948. vertex_normal.y /= radiusY;
  37949. vertex_normal.z /= radiusZ;
  37950. vertex_normal.normalize();
  37951. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37952. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37953. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37954. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37955. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37956. uvs.push(uv_interp.x, uv_interp.y);
  37957. // push each vertex has member of a face
  37958. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37959. indices.push(current_indice);
  37960. current_indice++;
  37961. };
  37962. for (var i2 = 0; i2 < subdivisions; i2++) {
  37963. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37964. // face : (i1,i2) for /\ :
  37965. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37966. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37967. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37968. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37969. if (i1 + i2 + 1 < subdivisions) {
  37970. // face : (i1,i2)' for \/ :
  37971. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37972. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37973. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37974. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37975. }
  37976. }
  37977. }
  37978. }
  37979. // Sides
  37980. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37981. // Result
  37982. var vertexData = new VertexData();
  37983. vertexData.indices = indices;
  37984. vertexData.positions = positions;
  37985. vertexData.normals = normals;
  37986. vertexData.uvs = uvs;
  37987. return vertexData;
  37988. };
  37989. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37990. /**
  37991. * Creates the VertexData for a Polyhedron
  37992. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37993. * * type provided types are:
  37994. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37995. * * 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)
  37996. * * size the size of the IcoSphere, optional default 1
  37997. * * sizeX allows stretching in the x direction, optional, default size
  37998. * * sizeY allows stretching in the y direction, optional, default size
  37999. * * sizeZ allows stretching in the z direction, optional, default size
  38000. * * 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
  38001. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38002. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38003. * * flat when true creates a flat shaded mesh, optional, default true
  38004. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38005. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38006. * * 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)
  38007. * * 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)
  38008. * @returns the VertexData of the Polyhedron
  38009. */
  38010. VertexData.CreatePolyhedron = function (options) {
  38011. // provided polyhedron types :
  38012. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38013. // 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)
  38014. var polyhedra = [];
  38015. 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]] };
  38016. 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]] };
  38017. polyhedra[2] = {
  38018. 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]],
  38019. 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]]
  38020. };
  38021. polyhedra[3] = {
  38022. 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]],
  38023. 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]]
  38024. };
  38025. polyhedra[4] = {
  38026. 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]],
  38027. 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]]
  38028. };
  38029. 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]] };
  38030. 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]] };
  38031. 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]] };
  38032. 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]] };
  38033. 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]] };
  38034. 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]] };
  38035. 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]] };
  38036. 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]] };
  38037. 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]] };
  38038. polyhedra[14] = {
  38039. 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]],
  38040. 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]]
  38041. };
  38042. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38043. var size = options.size;
  38044. var sizeX = options.sizeX || size || 1;
  38045. var sizeY = options.sizeY || size || 1;
  38046. var sizeZ = options.sizeZ || size || 1;
  38047. var data = options.custom || polyhedra[type];
  38048. var nbfaces = data.face.length;
  38049. var faceUV = options.faceUV || new Array(nbfaces);
  38050. var faceColors = options.faceColors;
  38051. var flat = (options.flat === undefined) ? true : options.flat;
  38052. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38053. var positions = new Array();
  38054. var indices = new Array();
  38055. var normals = new Array();
  38056. var uvs = new Array();
  38057. var colors = new Array();
  38058. var index = 0;
  38059. var faceIdx = 0; // face cursor in the array "indexes"
  38060. var indexes = new Array();
  38061. var i = 0;
  38062. var f = 0;
  38063. var u, v, ang, x, y, tmp;
  38064. // default face colors and UV if undefined
  38065. if (flat) {
  38066. for (f = 0; f < nbfaces; f++) {
  38067. if (faceColors && faceColors[f] === undefined) {
  38068. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38069. }
  38070. if (faceUV && faceUV[f] === undefined) {
  38071. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38072. }
  38073. }
  38074. }
  38075. if (!flat) {
  38076. for (i = 0; i < data.vertex.length; i++) {
  38077. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38078. uvs.push(0, 0);
  38079. }
  38080. for (f = 0; f < nbfaces; f++) {
  38081. for (i = 0; i < data.face[f].length - 2; i++) {
  38082. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38083. }
  38084. }
  38085. }
  38086. else {
  38087. for (f = 0; f < nbfaces; f++) {
  38088. var fl = data.face[f].length; // number of vertices of the current face
  38089. ang = 2 * Math.PI / fl;
  38090. x = 0.5 * Math.tan(ang / 2);
  38091. y = 0.5;
  38092. // positions, uvs, colors
  38093. for (i = 0; i < fl; i++) {
  38094. // positions
  38095. 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);
  38096. indexes.push(index);
  38097. index++;
  38098. // uvs
  38099. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38100. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38101. uvs.push(u, v);
  38102. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38103. y = x * Math.sin(ang) + y * Math.cos(ang);
  38104. x = tmp;
  38105. // colors
  38106. if (faceColors) {
  38107. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38108. }
  38109. }
  38110. // indices from indexes
  38111. for (i = 0; i < fl - 2; i++) {
  38112. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38113. }
  38114. faceIdx += fl;
  38115. }
  38116. }
  38117. VertexData.ComputeNormals(positions, indices, normals);
  38118. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38119. var vertexData = new VertexData();
  38120. vertexData.positions = positions;
  38121. vertexData.indices = indices;
  38122. vertexData.normals = normals;
  38123. vertexData.uvs = uvs;
  38124. if (faceColors && flat) {
  38125. vertexData.colors = colors;
  38126. }
  38127. return vertexData;
  38128. };
  38129. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38130. /**
  38131. * Creates the VertexData for a TorusKnot
  38132. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38133. * * radius the radius of the torus knot, optional, default 2
  38134. * * tube the thickness of the tube, optional, default 0.5
  38135. * * radialSegments the number of sides on each tube segments, optional, default 32
  38136. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38137. * * p the number of windings around the z axis, optional, default 2
  38138. * * q the number of windings around the x axis, optional, default 3
  38139. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38140. * * 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)
  38141. * * 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)
  38142. * @returns the VertexData of the Torus Knot
  38143. */
  38144. VertexData.CreateTorusKnot = function (options) {
  38145. var indices = new Array();
  38146. var positions = new Array();
  38147. var normals = new Array();
  38148. var uvs = new Array();
  38149. var radius = options.radius || 2;
  38150. var tube = options.tube || 0.5;
  38151. var radialSegments = options.radialSegments || 32;
  38152. var tubularSegments = options.tubularSegments || 32;
  38153. var p = options.p || 2;
  38154. var q = options.q || 3;
  38155. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38156. // Helper
  38157. var getPos = function (angle) {
  38158. var cu = Math.cos(angle);
  38159. var su = Math.sin(angle);
  38160. var quOverP = q / p * angle;
  38161. var cs = Math.cos(quOverP);
  38162. var tx = radius * (2 + cs) * 0.5 * cu;
  38163. var ty = radius * (2 + cs) * su * 0.5;
  38164. var tz = radius * Math.sin(quOverP) * 0.5;
  38165. return new BABYLON.Vector3(tx, ty, tz);
  38166. };
  38167. // Vertices
  38168. var i;
  38169. var j;
  38170. for (i = 0; i <= radialSegments; i++) {
  38171. var modI = i % radialSegments;
  38172. var u = modI / radialSegments * 2 * p * Math.PI;
  38173. var p1 = getPos(u);
  38174. var p2 = getPos(u + 0.01);
  38175. var tang = p2.subtract(p1);
  38176. var n = p2.add(p1);
  38177. var bitan = BABYLON.Vector3.Cross(tang, n);
  38178. n = BABYLON.Vector3.Cross(bitan, tang);
  38179. bitan.normalize();
  38180. n.normalize();
  38181. for (j = 0; j < tubularSegments; j++) {
  38182. var modJ = j % tubularSegments;
  38183. var v = modJ / tubularSegments * 2 * Math.PI;
  38184. var cx = -tube * Math.cos(v);
  38185. var cy = tube * Math.sin(v);
  38186. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38187. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38188. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38189. uvs.push(i / radialSegments);
  38190. uvs.push(j / tubularSegments);
  38191. }
  38192. }
  38193. for (i = 0; i < radialSegments; i++) {
  38194. for (j = 0; j < tubularSegments; j++) {
  38195. var jNext = (j + 1) % tubularSegments;
  38196. var a = i * tubularSegments + j;
  38197. var b = (i + 1) * tubularSegments + j;
  38198. var c = (i + 1) * tubularSegments + jNext;
  38199. var d = i * tubularSegments + jNext;
  38200. indices.push(d);
  38201. indices.push(b);
  38202. indices.push(a);
  38203. indices.push(d);
  38204. indices.push(c);
  38205. indices.push(b);
  38206. }
  38207. }
  38208. // Normals
  38209. VertexData.ComputeNormals(positions, indices, normals);
  38210. // Sides
  38211. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38212. // Result
  38213. var vertexData = new VertexData();
  38214. vertexData.indices = indices;
  38215. vertexData.positions = positions;
  38216. vertexData.normals = normals;
  38217. vertexData.uvs = uvs;
  38218. return vertexData;
  38219. };
  38220. // Tools
  38221. /**
  38222. * Compute normals for given positions and indices
  38223. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38224. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38225. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38226. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38227. * * facetNormals : optional array of facet normals (vector3)
  38228. * * facetPositions : optional array of facet positions (vector3)
  38229. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38230. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38231. * * bInfo : optional bounding info, required for facetPartitioning computation
  38232. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38233. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38234. * * useRightHandedSystem: optional boolean to for right handed system computation
  38235. * * depthSort : optional boolean to enable the facet depth sort computation
  38236. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38237. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38238. */
  38239. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38240. // temporary scalar variables
  38241. var index = 0; // facet index
  38242. var p1p2x = 0.0; // p1p2 vector x coordinate
  38243. var p1p2y = 0.0; // p1p2 vector y coordinate
  38244. var p1p2z = 0.0; // p1p2 vector z coordinate
  38245. var p3p2x = 0.0; // p3p2 vector x coordinate
  38246. var p3p2y = 0.0; // p3p2 vector y coordinate
  38247. var p3p2z = 0.0; // p3p2 vector z coordinate
  38248. var faceNormalx = 0.0; // facet normal x coordinate
  38249. var faceNormaly = 0.0; // facet normal y coordinate
  38250. var faceNormalz = 0.0; // facet normal z coordinate
  38251. var length = 0.0; // facet normal length before normalization
  38252. var v1x = 0; // vector1 x index in the positions array
  38253. var v1y = 0; // vector1 y index in the positions array
  38254. var v1z = 0; // vector1 z index in the positions array
  38255. var v2x = 0; // vector2 x index in the positions array
  38256. var v2y = 0; // vector2 y index in the positions array
  38257. var v2z = 0; // vector2 z index in the positions array
  38258. var v3x = 0; // vector3 x index in the positions array
  38259. var v3y = 0; // vector3 y index in the positions array
  38260. var v3z = 0; // vector3 z index in the positions array
  38261. var computeFacetNormals = false;
  38262. var computeFacetPositions = false;
  38263. var computeFacetPartitioning = false;
  38264. var computeDepthSort = false;
  38265. var faceNormalSign = 1;
  38266. var ratio = 0;
  38267. var distanceTo = null;
  38268. if (options) {
  38269. computeFacetNormals = (options.facetNormals) ? true : false;
  38270. computeFacetPositions = (options.facetPositions) ? true : false;
  38271. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38272. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38273. ratio = options.ratio || 0;
  38274. computeDepthSort = (options.depthSort) ? true : false;
  38275. distanceTo = (options.distanceTo);
  38276. if (computeDepthSort) {
  38277. if (distanceTo === undefined) {
  38278. distanceTo = BABYLON.Vector3.Zero();
  38279. }
  38280. var depthSortedFacets = options.depthSortedFacets;
  38281. }
  38282. }
  38283. // facetPartitioning reinit if needed
  38284. var xSubRatio = 0;
  38285. var ySubRatio = 0;
  38286. var zSubRatio = 0;
  38287. var subSq = 0;
  38288. if (computeFacetPartitioning && options && options.bbSize) {
  38289. var ox = 0; // X partitioning index for facet position
  38290. var oy = 0; // Y partinioning index for facet position
  38291. var oz = 0; // Z partinioning index for facet position
  38292. var b1x = 0; // X partitioning index for facet v1 vertex
  38293. var b1y = 0; // Y partitioning index for facet v1 vertex
  38294. var b1z = 0; // z partitioning index for facet v1 vertex
  38295. var b2x = 0; // X partitioning index for facet v2 vertex
  38296. var b2y = 0; // Y partitioning index for facet v2 vertex
  38297. var b2z = 0; // Z partitioning index for facet v2 vertex
  38298. var b3x = 0; // X partitioning index for facet v3 vertex
  38299. var b3y = 0; // Y partitioning index for facet v3 vertex
  38300. var b3z = 0; // Z partitioning index for facet v3 vertex
  38301. var block_idx_o = 0; // facet barycenter block index
  38302. var block_idx_v1 = 0; // v1 vertex block index
  38303. var block_idx_v2 = 0; // v2 vertex block index
  38304. var block_idx_v3 = 0; // v3 vertex block index
  38305. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38306. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38307. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38308. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38309. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38310. subSq = options.subDiv.max * options.subDiv.max;
  38311. options.facetPartitioning.length = 0;
  38312. }
  38313. // reset the normals
  38314. for (index = 0; index < positions.length; index++) {
  38315. normals[index] = 0.0;
  38316. }
  38317. // Loop : 1 indice triplet = 1 facet
  38318. var nbFaces = (indices.length / 3) | 0;
  38319. for (index = 0; index < nbFaces; index++) {
  38320. // get the indexes of the coordinates of each vertex of the facet
  38321. v1x = indices[index * 3] * 3;
  38322. v1y = v1x + 1;
  38323. v1z = v1x + 2;
  38324. v2x = indices[index * 3 + 1] * 3;
  38325. v2y = v2x + 1;
  38326. v2z = v2x + 2;
  38327. v3x = indices[index * 3 + 2] * 3;
  38328. v3y = v3x + 1;
  38329. v3z = v3x + 2;
  38330. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38331. p1p2y = positions[v1y] - positions[v2y];
  38332. p1p2z = positions[v1z] - positions[v2z];
  38333. p3p2x = positions[v3x] - positions[v2x];
  38334. p3p2y = positions[v3y] - positions[v2y];
  38335. p3p2z = positions[v3z] - positions[v2z];
  38336. // compute the face normal with the cross product
  38337. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38338. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38339. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38340. // normalize this normal and store it in the array facetData
  38341. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38342. length = (length === 0) ? 1.0 : length;
  38343. faceNormalx /= length;
  38344. faceNormaly /= length;
  38345. faceNormalz /= length;
  38346. if (computeFacetNormals && options) {
  38347. options.facetNormals[index].x = faceNormalx;
  38348. options.facetNormals[index].y = faceNormaly;
  38349. options.facetNormals[index].z = faceNormalz;
  38350. }
  38351. if (computeFacetPositions && options) {
  38352. // compute and the facet barycenter coordinates in the array facetPositions
  38353. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38354. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38355. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38356. }
  38357. if (computeFacetPartitioning && options) {
  38358. // store the facet indexes in arrays in the main facetPartitioning array :
  38359. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38360. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38361. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38362. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38363. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38364. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38365. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38366. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38367. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38368. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38369. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38370. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38371. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38372. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38373. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38374. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38375. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38376. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38377. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38378. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38379. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38380. // push each facet index in each block containing the vertex
  38381. options.facetPartitioning[block_idx_v1].push(index);
  38382. if (block_idx_v2 != block_idx_v1) {
  38383. options.facetPartitioning[block_idx_v2].push(index);
  38384. }
  38385. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38386. options.facetPartitioning[block_idx_v3].push(index);
  38387. }
  38388. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38389. options.facetPartitioning[block_idx_o].push(index);
  38390. }
  38391. }
  38392. if (computeDepthSort && options && options.facetPositions) {
  38393. var dsf = depthSortedFacets[index];
  38394. dsf.ind = index * 3;
  38395. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38396. }
  38397. // compute the normals anyway
  38398. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38399. normals[v1y] += faceNormaly;
  38400. normals[v1z] += faceNormalz;
  38401. normals[v2x] += faceNormalx;
  38402. normals[v2y] += faceNormaly;
  38403. normals[v2z] += faceNormalz;
  38404. normals[v3x] += faceNormalx;
  38405. normals[v3y] += faceNormaly;
  38406. normals[v3z] += faceNormalz;
  38407. }
  38408. // last normalization of each normal
  38409. for (index = 0; index < normals.length / 3; index++) {
  38410. faceNormalx = normals[index * 3];
  38411. faceNormaly = normals[index * 3 + 1];
  38412. faceNormalz = normals[index * 3 + 2];
  38413. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38414. length = (length === 0) ? 1.0 : length;
  38415. faceNormalx /= length;
  38416. faceNormaly /= length;
  38417. faceNormalz /= length;
  38418. normals[index * 3] = faceNormalx;
  38419. normals[index * 3 + 1] = faceNormaly;
  38420. normals[index * 3 + 2] = faceNormalz;
  38421. }
  38422. };
  38423. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38424. var li = indices.length;
  38425. var ln = normals.length;
  38426. var i;
  38427. var n;
  38428. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38429. switch (sideOrientation) {
  38430. case BABYLON.Mesh.FRONTSIDE:
  38431. // nothing changed
  38432. break;
  38433. case BABYLON.Mesh.BACKSIDE:
  38434. var tmp;
  38435. // indices
  38436. for (i = 0; i < li; i += 3) {
  38437. tmp = indices[i];
  38438. indices[i] = indices[i + 2];
  38439. indices[i + 2] = tmp;
  38440. }
  38441. // normals
  38442. for (n = 0; n < ln; n++) {
  38443. normals[n] = -normals[n];
  38444. }
  38445. break;
  38446. case BABYLON.Mesh.DOUBLESIDE:
  38447. // positions
  38448. var lp = positions.length;
  38449. var l = lp / 3;
  38450. for (var p = 0; p < lp; p++) {
  38451. positions[lp + p] = positions[p];
  38452. }
  38453. // indices
  38454. for (i = 0; i < li; i += 3) {
  38455. indices[i + li] = indices[i + 2] + l;
  38456. indices[i + 1 + li] = indices[i + 1] + l;
  38457. indices[i + 2 + li] = indices[i] + l;
  38458. }
  38459. // normals
  38460. for (n = 0; n < ln; n++) {
  38461. normals[ln + n] = -normals[n];
  38462. }
  38463. // uvs
  38464. var lu = uvs.length;
  38465. var u = 0;
  38466. for (u = 0; u < lu; u++) {
  38467. uvs[u + lu] = uvs[u];
  38468. }
  38469. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38470. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38471. u = 0;
  38472. for (i = 0; i < lu / 2; i++) {
  38473. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38474. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38475. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38476. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38477. u += 2;
  38478. }
  38479. break;
  38480. }
  38481. };
  38482. /**
  38483. * Applies VertexData created from the imported parameters to the geometry
  38484. * @param parsedVertexData the parsed data from an imported file
  38485. * @param geometry the geometry to apply the VertexData to
  38486. */
  38487. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38488. var vertexData = new VertexData();
  38489. // positions
  38490. var positions = parsedVertexData.positions;
  38491. if (positions) {
  38492. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38493. }
  38494. // normals
  38495. var normals = parsedVertexData.normals;
  38496. if (normals) {
  38497. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38498. }
  38499. // tangents
  38500. var tangents = parsedVertexData.tangents;
  38501. if (tangents) {
  38502. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38503. }
  38504. // uvs
  38505. var uvs = parsedVertexData.uvs;
  38506. if (uvs) {
  38507. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38508. }
  38509. // uv2s
  38510. var uv2s = parsedVertexData.uv2s;
  38511. if (uv2s) {
  38512. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38513. }
  38514. // uv3s
  38515. var uv3s = parsedVertexData.uv3s;
  38516. if (uv3s) {
  38517. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38518. }
  38519. // uv4s
  38520. var uv4s = parsedVertexData.uv4s;
  38521. if (uv4s) {
  38522. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38523. }
  38524. // uv5s
  38525. var uv5s = parsedVertexData.uv5s;
  38526. if (uv5s) {
  38527. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38528. }
  38529. // uv6s
  38530. var uv6s = parsedVertexData.uv6s;
  38531. if (uv6s) {
  38532. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38533. }
  38534. // colors
  38535. var colors = parsedVertexData.colors;
  38536. if (colors) {
  38537. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38538. }
  38539. // matricesIndices
  38540. var matricesIndices = parsedVertexData.matricesIndices;
  38541. if (matricesIndices) {
  38542. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38543. }
  38544. // matricesWeights
  38545. var matricesWeights = parsedVertexData.matricesWeights;
  38546. if (matricesWeights) {
  38547. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38548. }
  38549. // indices
  38550. var indices = parsedVertexData.indices;
  38551. if (indices) {
  38552. vertexData.indices = indices;
  38553. }
  38554. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38555. };
  38556. return VertexData;
  38557. }());
  38558. BABYLON.VertexData = VertexData;
  38559. })(BABYLON || (BABYLON = {}));
  38560. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38561. var BABYLON;
  38562. (function (BABYLON) {
  38563. /**
  38564. * Class used to store geometry data (vertex buffers + index buffer)
  38565. */
  38566. var Geometry = /** @class */ (function () {
  38567. /**
  38568. * Creates a new geometry
  38569. * @param id defines the unique ID
  38570. * @param scene defines the hosting scene
  38571. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38572. * @param updatable defines if geometry must be updatable (false by default)
  38573. * @param mesh defines the mesh that will be associated with the geometry
  38574. */
  38575. function Geometry(id, scene, vertexData, updatable, mesh) {
  38576. if (updatable === void 0) { updatable = false; }
  38577. if (mesh === void 0) { mesh = null; }
  38578. /**
  38579. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38580. */
  38581. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38582. this._totalVertices = 0;
  38583. this._isDisposed = false;
  38584. this._indexBufferIsUpdatable = false;
  38585. this.id = id;
  38586. this._engine = scene.getEngine();
  38587. this._meshes = [];
  38588. this._scene = scene;
  38589. //Init vertex buffer cache
  38590. this._vertexBuffers = {};
  38591. this._indices = [];
  38592. this._updatable = updatable;
  38593. // vertexData
  38594. if (vertexData) {
  38595. this.setAllVerticesData(vertexData, updatable);
  38596. }
  38597. else {
  38598. this._totalVertices = 0;
  38599. this._indices = [];
  38600. }
  38601. if (this._engine.getCaps().vertexArrayObject) {
  38602. this._vertexArrayObjects = {};
  38603. }
  38604. // applyToMesh
  38605. if (mesh) {
  38606. if (mesh.getClassName() === "LinesMesh") {
  38607. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38608. this._updateExtend();
  38609. }
  38610. this.applyToMesh(mesh);
  38611. mesh.computeWorldMatrix(true);
  38612. }
  38613. }
  38614. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38615. /**
  38616. * 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
  38617. */
  38618. get: function () {
  38619. return this._boundingBias;
  38620. },
  38621. /**
  38622. * 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
  38623. */
  38624. set: function (value) {
  38625. if (this._boundingBias && this._boundingBias.equals(value)) {
  38626. return;
  38627. }
  38628. this._boundingBias = value.clone();
  38629. this._updateBoundingInfo(true, null);
  38630. },
  38631. enumerable: true,
  38632. configurable: true
  38633. });
  38634. /**
  38635. * Static function used to attach a new empty geometry to a mesh
  38636. * @param mesh defines the mesh to attach the geometry to
  38637. * @returns the new {BABYLON.Geometry}
  38638. */
  38639. Geometry.CreateGeometryForMesh = function (mesh) {
  38640. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38641. geometry.applyToMesh(mesh);
  38642. return geometry;
  38643. };
  38644. Object.defineProperty(Geometry.prototype, "extend", {
  38645. /**
  38646. * Gets the current extend of the geometry
  38647. */
  38648. get: function () {
  38649. return this._extend;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. /**
  38655. * Gets the hosting scene
  38656. * @returns the hosting {BABYLON.Scene}
  38657. */
  38658. Geometry.prototype.getScene = function () {
  38659. return this._scene;
  38660. };
  38661. /**
  38662. * Gets the hosting engine
  38663. * @returns the hosting {BABYLON.Engine}
  38664. */
  38665. Geometry.prototype.getEngine = function () {
  38666. return this._engine;
  38667. };
  38668. /**
  38669. * Defines if the geometry is ready to use
  38670. * @returns true if the geometry is ready to be used
  38671. */
  38672. Geometry.prototype.isReady = function () {
  38673. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38674. };
  38675. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38676. /**
  38677. * Gets a value indicating that the geometry should not be serialized
  38678. */
  38679. get: function () {
  38680. for (var index = 0; index < this._meshes.length; index++) {
  38681. if (!this._meshes[index].doNotSerialize) {
  38682. return false;
  38683. }
  38684. }
  38685. return true;
  38686. },
  38687. enumerable: true,
  38688. configurable: true
  38689. });
  38690. /** @hidden */
  38691. Geometry.prototype._rebuild = function () {
  38692. if (this._vertexArrayObjects) {
  38693. this._vertexArrayObjects = {};
  38694. }
  38695. // Index buffer
  38696. if (this._meshes.length !== 0 && this._indices) {
  38697. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38698. }
  38699. // Vertex buffers
  38700. for (var key in this._vertexBuffers) {
  38701. var vertexBuffer = this._vertexBuffers[key];
  38702. vertexBuffer._rebuild();
  38703. }
  38704. };
  38705. /**
  38706. * Affects all geometry data in one call
  38707. * @param vertexData defines the geometry data
  38708. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38709. */
  38710. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38711. vertexData.applyToGeometry(this, updatable);
  38712. this.notifyUpdate();
  38713. };
  38714. /**
  38715. * Set specific vertex data
  38716. * @param kind defines the data kind (Position, normal, etc...)
  38717. * @param data defines the vertex data to use
  38718. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38719. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38720. */
  38721. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38722. if (updatable === void 0) { updatable = false; }
  38723. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38724. this.setVerticesBuffer(buffer);
  38725. };
  38726. /**
  38727. * Removes a specific vertex data
  38728. * @param kind defines the data kind (Position, normal, etc...)
  38729. */
  38730. Geometry.prototype.removeVerticesData = function (kind) {
  38731. if (this._vertexBuffers[kind]) {
  38732. this._vertexBuffers[kind].dispose();
  38733. delete this._vertexBuffers[kind];
  38734. }
  38735. };
  38736. /**
  38737. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38738. * @param buffer defines the vertex buffer to use
  38739. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38740. */
  38741. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38742. if (totalVertices === void 0) { totalVertices = null; }
  38743. var kind = buffer.getKind();
  38744. if (this._vertexBuffers[kind]) {
  38745. this._vertexBuffers[kind].dispose();
  38746. }
  38747. this._vertexBuffers[kind] = buffer;
  38748. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38749. var data = buffer.getData();
  38750. if (totalVertices != null) {
  38751. this._totalVertices = totalVertices;
  38752. }
  38753. else {
  38754. if (data != null) {
  38755. this._totalVertices = data.length / (buffer.byteStride / 4);
  38756. }
  38757. }
  38758. this._updateExtend(data);
  38759. this._resetPointsArrayCache();
  38760. var meshes = this._meshes;
  38761. var numOfMeshes = meshes.length;
  38762. for (var index = 0; index < numOfMeshes; index++) {
  38763. var mesh = meshes[index];
  38764. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38765. mesh._createGlobalSubMesh(false);
  38766. mesh.computeWorldMatrix(true);
  38767. }
  38768. }
  38769. this.notifyUpdate(kind);
  38770. if (this._vertexArrayObjects) {
  38771. this._disposeVertexArrayObjects();
  38772. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38773. }
  38774. };
  38775. /**
  38776. * Update a specific vertex buffer
  38777. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38778. * It will do nothing if the buffer is not updatable
  38779. * @param kind defines the data kind (Position, normal, etc...)
  38780. * @param data defines the data to use
  38781. * @param offset defines the offset in the target buffer where to store the data
  38782. * @param useBytes set to true if the offset is in bytes
  38783. */
  38784. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38785. if (useBytes === void 0) { useBytes = false; }
  38786. var vertexBuffer = this.getVertexBuffer(kind);
  38787. if (!vertexBuffer) {
  38788. return;
  38789. }
  38790. vertexBuffer.updateDirectly(data, offset, useBytes);
  38791. this.notifyUpdate(kind);
  38792. };
  38793. /**
  38794. * Update a specific vertex buffer
  38795. * This function will create a new buffer if the current one is not updatable
  38796. * @param kind defines the data kind (Position, normal, etc...)
  38797. * @param data defines the data to use
  38798. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38799. */
  38800. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38801. if (updateExtends === void 0) { updateExtends = false; }
  38802. var vertexBuffer = this.getVertexBuffer(kind);
  38803. if (!vertexBuffer) {
  38804. return;
  38805. }
  38806. vertexBuffer.update(data);
  38807. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38808. this._updateBoundingInfo(updateExtends, data);
  38809. }
  38810. this.notifyUpdate(kind);
  38811. };
  38812. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38813. if (updateExtends) {
  38814. this._updateExtend(data);
  38815. }
  38816. var meshes = this._meshes;
  38817. var numOfMeshes = meshes.length;
  38818. this._resetPointsArrayCache();
  38819. for (var index = 0; index < numOfMeshes; index++) {
  38820. var mesh = meshes[index];
  38821. if (updateExtends) {
  38822. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38823. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38824. var subMesh = mesh.subMeshes[subIndex];
  38825. subMesh.refreshBoundingInfo();
  38826. }
  38827. }
  38828. }
  38829. };
  38830. /** @hidden */
  38831. Geometry.prototype._bind = function (effect, indexToBind) {
  38832. if (!effect) {
  38833. return;
  38834. }
  38835. if (indexToBind === undefined) {
  38836. indexToBind = this._indexBuffer;
  38837. }
  38838. var vbs = this.getVertexBuffers();
  38839. if (!vbs) {
  38840. return;
  38841. }
  38842. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38843. this._engine.bindBuffers(vbs, indexToBind, effect);
  38844. return;
  38845. }
  38846. // Using VAO
  38847. if (!this._vertexArrayObjects[effect.key]) {
  38848. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38849. }
  38850. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38851. };
  38852. /**
  38853. * Gets total number of vertices
  38854. * @returns the total number of vertices
  38855. */
  38856. Geometry.prototype.getTotalVertices = function () {
  38857. if (!this.isReady()) {
  38858. return 0;
  38859. }
  38860. return this._totalVertices;
  38861. };
  38862. /**
  38863. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38864. * @param kind defines the data kind (Position, normal, etc...)
  38865. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38866. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38867. * @returns a float array containing vertex data
  38868. */
  38869. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38870. var vertexBuffer = this.getVertexBuffer(kind);
  38871. if (!vertexBuffer) {
  38872. return null;
  38873. }
  38874. var data = vertexBuffer.getData();
  38875. if (!data) {
  38876. return null;
  38877. }
  38878. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38879. var count = this._totalVertices * vertexBuffer.getSize();
  38880. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38881. var copy_1 = new Array(count);
  38882. vertexBuffer.forEach(count, function (value, index) {
  38883. copy_1[index] = value;
  38884. });
  38885. return copy_1;
  38886. }
  38887. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38888. if (data instanceof Array) {
  38889. var offset = vertexBuffer.byteOffset / 4;
  38890. return BABYLON.Tools.Slice(data, offset, offset + count);
  38891. }
  38892. else if (data instanceof ArrayBuffer) {
  38893. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38894. }
  38895. else {
  38896. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38897. }
  38898. }
  38899. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38900. return BABYLON.Tools.Slice(data);
  38901. }
  38902. return data;
  38903. };
  38904. /**
  38905. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38906. * @param kind defines the data kind (Position, normal, etc...)
  38907. * @returns true if the vertex buffer with the specified kind is updatable
  38908. */
  38909. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38910. var vb = this._vertexBuffers[kind];
  38911. if (!vb) {
  38912. return false;
  38913. }
  38914. return vb.isUpdatable();
  38915. };
  38916. /**
  38917. * Gets a specific vertex buffer
  38918. * @param kind defines the data kind (Position, normal, etc...)
  38919. * @returns a {BABYLON.VertexBuffer}
  38920. */
  38921. Geometry.prototype.getVertexBuffer = function (kind) {
  38922. if (!this.isReady()) {
  38923. return null;
  38924. }
  38925. return this._vertexBuffers[kind];
  38926. };
  38927. /**
  38928. * Returns all vertex buffers
  38929. * @return an object holding all vertex buffers indexed by kind
  38930. */
  38931. Geometry.prototype.getVertexBuffers = function () {
  38932. if (!this.isReady()) {
  38933. return null;
  38934. }
  38935. return this._vertexBuffers;
  38936. };
  38937. /**
  38938. * Gets a boolean indicating if specific vertex buffer is present
  38939. * @param kind defines the data kind (Position, normal, etc...)
  38940. * @returns true if data is present
  38941. */
  38942. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38943. if (!this._vertexBuffers) {
  38944. if (this._delayInfo) {
  38945. return this._delayInfo.indexOf(kind) !== -1;
  38946. }
  38947. return false;
  38948. }
  38949. return this._vertexBuffers[kind] !== undefined;
  38950. };
  38951. /**
  38952. * Gets a list of all attached data kinds (Position, normal, etc...)
  38953. * @returns a list of string containing all kinds
  38954. */
  38955. Geometry.prototype.getVerticesDataKinds = function () {
  38956. var result = [];
  38957. var kind;
  38958. if (!this._vertexBuffers && this._delayInfo) {
  38959. for (kind in this._delayInfo) {
  38960. result.push(kind);
  38961. }
  38962. }
  38963. else {
  38964. for (kind in this._vertexBuffers) {
  38965. result.push(kind);
  38966. }
  38967. }
  38968. return result;
  38969. };
  38970. /**
  38971. * Update index buffer
  38972. * @param indices defines the indices to store in the index buffer
  38973. * @param offset defines the offset in the target buffer where to store the data
  38974. */
  38975. Geometry.prototype.updateIndices = function (indices, offset) {
  38976. if (!this._indexBuffer) {
  38977. return;
  38978. }
  38979. if (!this._indexBufferIsUpdatable) {
  38980. this.setIndices(indices, null, true);
  38981. }
  38982. else {
  38983. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38984. }
  38985. };
  38986. /**
  38987. * Creates a new index buffer
  38988. * @param indices defines the indices to store in the index buffer
  38989. * @param totalVertices defines the total number of vertices (could be null)
  38990. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38991. */
  38992. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38993. if (totalVertices === void 0) { totalVertices = null; }
  38994. if (updatable === void 0) { updatable = false; }
  38995. if (this._indexBuffer) {
  38996. this._engine._releaseBuffer(this._indexBuffer);
  38997. }
  38998. this._disposeVertexArrayObjects();
  38999. this._indices = indices;
  39000. this._indexBufferIsUpdatable = updatable;
  39001. if (this._meshes.length !== 0 && this._indices) {
  39002. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39003. }
  39004. if (totalVertices != undefined) { // including null and undefined
  39005. this._totalVertices = totalVertices;
  39006. }
  39007. var meshes = this._meshes;
  39008. var numOfMeshes = meshes.length;
  39009. for (var index = 0; index < numOfMeshes; index++) {
  39010. meshes[index]._createGlobalSubMesh(true);
  39011. }
  39012. this.notifyUpdate();
  39013. };
  39014. /**
  39015. * Return the total number of indices
  39016. * @returns the total number of indices
  39017. */
  39018. Geometry.prototype.getTotalIndices = function () {
  39019. if (!this.isReady()) {
  39020. return 0;
  39021. }
  39022. return this._indices.length;
  39023. };
  39024. /**
  39025. * Gets the index buffer array
  39026. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39027. * @returns the index buffer array
  39028. */
  39029. Geometry.prototype.getIndices = function (copyWhenShared) {
  39030. if (!this.isReady()) {
  39031. return null;
  39032. }
  39033. var orig = this._indices;
  39034. if (!copyWhenShared || this._meshes.length === 1) {
  39035. return orig;
  39036. }
  39037. else {
  39038. var len = orig.length;
  39039. var copy = [];
  39040. for (var i = 0; i < len; i++) {
  39041. copy.push(orig[i]);
  39042. }
  39043. return copy;
  39044. }
  39045. };
  39046. /**
  39047. * Gets the index buffer
  39048. * @return the index buffer
  39049. */
  39050. Geometry.prototype.getIndexBuffer = function () {
  39051. if (!this.isReady()) {
  39052. return null;
  39053. }
  39054. return this._indexBuffer;
  39055. };
  39056. /** @hidden */
  39057. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39058. if (effect === void 0) { effect = null; }
  39059. if (!effect || !this._vertexArrayObjects) {
  39060. return;
  39061. }
  39062. if (this._vertexArrayObjects[effect.key]) {
  39063. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39064. delete this._vertexArrayObjects[effect.key];
  39065. }
  39066. };
  39067. /**
  39068. * Release the associated resources for a specific mesh
  39069. * @param mesh defines the source mesh
  39070. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39071. */
  39072. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39073. var meshes = this._meshes;
  39074. var index = meshes.indexOf(mesh);
  39075. if (index === -1) {
  39076. return;
  39077. }
  39078. meshes.splice(index, 1);
  39079. mesh._geometry = null;
  39080. if (meshes.length === 0 && shouldDispose) {
  39081. this.dispose();
  39082. }
  39083. };
  39084. /**
  39085. * Apply current geometry to a given mesh
  39086. * @param mesh defines the mesh to apply geometry to
  39087. */
  39088. Geometry.prototype.applyToMesh = function (mesh) {
  39089. if (mesh._geometry === this) {
  39090. return;
  39091. }
  39092. var previousGeometry = mesh._geometry;
  39093. if (previousGeometry) {
  39094. previousGeometry.releaseForMesh(mesh);
  39095. }
  39096. var meshes = this._meshes;
  39097. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39098. mesh._geometry = this;
  39099. this._scene.pushGeometry(this);
  39100. meshes.push(mesh);
  39101. if (this.isReady()) {
  39102. this._applyToMesh(mesh);
  39103. }
  39104. else {
  39105. mesh._boundingInfo = this._boundingInfo;
  39106. }
  39107. };
  39108. Geometry.prototype._updateExtend = function (data) {
  39109. if (data === void 0) { data = null; }
  39110. if (!data) {
  39111. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39112. }
  39113. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39114. };
  39115. Geometry.prototype._applyToMesh = function (mesh) {
  39116. var numOfMeshes = this._meshes.length;
  39117. // vertexBuffers
  39118. for (var kind in this._vertexBuffers) {
  39119. if (numOfMeshes === 1) {
  39120. this._vertexBuffers[kind].create();
  39121. }
  39122. var buffer = this._vertexBuffers[kind].getBuffer();
  39123. if (buffer)
  39124. buffer.references = numOfMeshes;
  39125. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39126. if (!this._extend) {
  39127. this._updateExtend();
  39128. }
  39129. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39130. mesh._createGlobalSubMesh(false);
  39131. //bounding info was just created again, world matrix should be applied again.
  39132. mesh._updateBoundingInfo();
  39133. }
  39134. }
  39135. // indexBuffer
  39136. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39137. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39138. }
  39139. if (this._indexBuffer) {
  39140. this._indexBuffer.references = numOfMeshes;
  39141. }
  39142. };
  39143. Geometry.prototype.notifyUpdate = function (kind) {
  39144. if (this.onGeometryUpdated) {
  39145. this.onGeometryUpdated(this, kind);
  39146. }
  39147. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39148. var mesh = _a[_i];
  39149. mesh._markSubMeshesAsAttributesDirty();
  39150. }
  39151. };
  39152. /**
  39153. * Load the geometry if it was flagged as delay loaded
  39154. * @param scene defines the hosting scene
  39155. * @param onLoaded defines a callback called when the geometry is loaded
  39156. */
  39157. Geometry.prototype.load = function (scene, onLoaded) {
  39158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39159. return;
  39160. }
  39161. if (this.isReady()) {
  39162. if (onLoaded) {
  39163. onLoaded();
  39164. }
  39165. return;
  39166. }
  39167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39168. this._queueLoad(scene, onLoaded);
  39169. };
  39170. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39171. var _this = this;
  39172. if (!this.delayLoadingFile) {
  39173. return;
  39174. }
  39175. scene._addPendingData(this);
  39176. scene._loadFile(this.delayLoadingFile, function (data) {
  39177. if (!_this._delayLoadingFunction) {
  39178. return;
  39179. }
  39180. _this._delayLoadingFunction(JSON.parse(data), _this);
  39181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39182. _this._delayInfo = [];
  39183. scene._removePendingData(_this);
  39184. var meshes = _this._meshes;
  39185. var numOfMeshes = meshes.length;
  39186. for (var index = 0; index < numOfMeshes; index++) {
  39187. _this._applyToMesh(meshes[index]);
  39188. }
  39189. if (onLoaded) {
  39190. onLoaded();
  39191. }
  39192. }, undefined, true);
  39193. };
  39194. /**
  39195. * Invert the geometry to move from a right handed system to a left handed one.
  39196. */
  39197. Geometry.prototype.toLeftHanded = function () {
  39198. // Flip faces
  39199. var tIndices = this.getIndices(false);
  39200. if (tIndices != null && tIndices.length > 0) {
  39201. for (var i = 0; i < tIndices.length; i += 3) {
  39202. var tTemp = tIndices[i + 0];
  39203. tIndices[i + 0] = tIndices[i + 2];
  39204. tIndices[i + 2] = tTemp;
  39205. }
  39206. this.setIndices(tIndices);
  39207. }
  39208. // Negate position.z
  39209. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39210. if (tPositions != null && tPositions.length > 0) {
  39211. for (var i = 0; i < tPositions.length; i += 3) {
  39212. tPositions[i + 2] = -tPositions[i + 2];
  39213. }
  39214. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39215. }
  39216. // Negate normal.z
  39217. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39218. if (tNormals != null && tNormals.length > 0) {
  39219. for (var i = 0; i < tNormals.length; i += 3) {
  39220. tNormals[i + 2] = -tNormals[i + 2];
  39221. }
  39222. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39223. }
  39224. };
  39225. // Cache
  39226. /** @hidden */
  39227. Geometry.prototype._resetPointsArrayCache = function () {
  39228. this._positions = null;
  39229. };
  39230. /** @hidden */
  39231. Geometry.prototype._generatePointsArray = function () {
  39232. if (this._positions)
  39233. return true;
  39234. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39235. if (!data || data.length === 0) {
  39236. return false;
  39237. }
  39238. this._positions = [];
  39239. for (var index = 0; index < data.length; index += 3) {
  39240. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39241. }
  39242. return true;
  39243. };
  39244. /**
  39245. * Gets a value indicating if the geometry is disposed
  39246. * @returns true if the geometry was disposed
  39247. */
  39248. Geometry.prototype.isDisposed = function () {
  39249. return this._isDisposed;
  39250. };
  39251. Geometry.prototype._disposeVertexArrayObjects = function () {
  39252. if (this._vertexArrayObjects) {
  39253. for (var kind in this._vertexArrayObjects) {
  39254. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39255. }
  39256. this._vertexArrayObjects = {};
  39257. }
  39258. };
  39259. /**
  39260. * Free all associated resources
  39261. */
  39262. Geometry.prototype.dispose = function () {
  39263. var meshes = this._meshes;
  39264. var numOfMeshes = meshes.length;
  39265. var index;
  39266. for (index = 0; index < numOfMeshes; index++) {
  39267. this.releaseForMesh(meshes[index]);
  39268. }
  39269. this._meshes = [];
  39270. this._disposeVertexArrayObjects();
  39271. for (var kind in this._vertexBuffers) {
  39272. this._vertexBuffers[kind].dispose();
  39273. }
  39274. this._vertexBuffers = {};
  39275. this._totalVertices = 0;
  39276. if (this._indexBuffer) {
  39277. this._engine._releaseBuffer(this._indexBuffer);
  39278. }
  39279. this._indexBuffer = null;
  39280. this._indices = [];
  39281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39282. this.delayLoadingFile = null;
  39283. this._delayLoadingFunction = null;
  39284. this._delayInfo = [];
  39285. this._boundingInfo = null;
  39286. this._scene.removeGeometry(this);
  39287. this._isDisposed = true;
  39288. };
  39289. /**
  39290. * Clone the current geometry into a new geometry
  39291. * @param id defines the unique ID of the new geometry
  39292. * @returns a new geometry object
  39293. */
  39294. Geometry.prototype.copy = function (id) {
  39295. var vertexData = new BABYLON.VertexData();
  39296. vertexData.indices = [];
  39297. var indices = this.getIndices();
  39298. if (indices) {
  39299. for (var index = 0; index < indices.length; index++) {
  39300. vertexData.indices.push(indices[index]);
  39301. }
  39302. }
  39303. var updatable = false;
  39304. var stopChecking = false;
  39305. var kind;
  39306. for (kind in this._vertexBuffers) {
  39307. // using slice() to make a copy of the array and not just reference it
  39308. var data = this.getVerticesData(kind);
  39309. if (data instanceof Float32Array) {
  39310. vertexData.set(new Float32Array(data), kind);
  39311. }
  39312. else {
  39313. vertexData.set(data.slice(0), kind);
  39314. }
  39315. if (!stopChecking) {
  39316. var vb = this.getVertexBuffer(kind);
  39317. if (vb) {
  39318. updatable = vb.isUpdatable();
  39319. stopChecking = !updatable;
  39320. }
  39321. }
  39322. }
  39323. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39324. geometry.delayLoadState = this.delayLoadState;
  39325. geometry.delayLoadingFile = this.delayLoadingFile;
  39326. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39327. for (kind in this._delayInfo) {
  39328. geometry._delayInfo = geometry._delayInfo || [];
  39329. geometry._delayInfo.push(kind);
  39330. }
  39331. // Bounding info
  39332. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39333. return geometry;
  39334. };
  39335. /**
  39336. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39337. * @return a JSON representation of the current geometry data (without the vertices data)
  39338. */
  39339. Geometry.prototype.serialize = function () {
  39340. var serializationObject = {};
  39341. serializationObject.id = this.id;
  39342. serializationObject.updatable = this._updatable;
  39343. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39344. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39345. }
  39346. return serializationObject;
  39347. };
  39348. Geometry.prototype.toNumberArray = function (origin) {
  39349. if (Array.isArray(origin)) {
  39350. return origin;
  39351. }
  39352. else {
  39353. return Array.prototype.slice.call(origin);
  39354. }
  39355. };
  39356. /**
  39357. * Serialize all vertices data into a JSON oject
  39358. * @returns a JSON representation of the current geometry data
  39359. */
  39360. Geometry.prototype.serializeVerticeData = function () {
  39361. var serializationObject = this.serialize();
  39362. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39363. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39364. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39365. serializationObject.positions._updatable = true;
  39366. }
  39367. }
  39368. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39369. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39371. serializationObject.normals._updatable = true;
  39372. }
  39373. }
  39374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39375. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39376. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39377. serializationObject.tangets._updatable = true;
  39378. }
  39379. }
  39380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39381. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39382. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39383. serializationObject.uvs._updatable = true;
  39384. }
  39385. }
  39386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39387. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39388. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39389. serializationObject.uv2s._updatable = true;
  39390. }
  39391. }
  39392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39393. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39394. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39395. serializationObject.uv3s._updatable = true;
  39396. }
  39397. }
  39398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39399. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39400. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39401. serializationObject.uv4s._updatable = true;
  39402. }
  39403. }
  39404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39405. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39406. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39407. serializationObject.uv5s._updatable = true;
  39408. }
  39409. }
  39410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39411. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39413. serializationObject.uv6s._updatable = true;
  39414. }
  39415. }
  39416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39417. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39419. serializationObject.colors._updatable = true;
  39420. }
  39421. }
  39422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39423. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39424. serializationObject.matricesIndices._isExpanded = true;
  39425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39426. serializationObject.matricesIndices._updatable = true;
  39427. }
  39428. }
  39429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39430. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39431. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39432. serializationObject.matricesWeights._updatable = true;
  39433. }
  39434. }
  39435. serializationObject.indices = this.toNumberArray(this.getIndices());
  39436. return serializationObject;
  39437. };
  39438. // Statics
  39439. /**
  39440. * Extracts a clone of a mesh geometry
  39441. * @param mesh defines the source mesh
  39442. * @param id defines the unique ID of the new geometry object
  39443. * @returns the new geometry object
  39444. */
  39445. Geometry.ExtractFromMesh = function (mesh, id) {
  39446. var geometry = mesh._geometry;
  39447. if (!geometry) {
  39448. return null;
  39449. }
  39450. return geometry.copy(id);
  39451. };
  39452. /**
  39453. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39454. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39455. * Be aware Math.random() could cause collisions, but:
  39456. * "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"
  39457. * @returns a string containing a new GUID
  39458. */
  39459. Geometry.RandomId = function () {
  39460. return BABYLON.Tools.RandomId();
  39461. };
  39462. /** @hidden */
  39463. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39464. var scene = mesh.getScene();
  39465. // Geometry
  39466. var geometryId = parsedGeometry.geometryId;
  39467. if (geometryId) {
  39468. var geometry = scene.getGeometryByID(geometryId);
  39469. if (geometry) {
  39470. geometry.applyToMesh(mesh);
  39471. }
  39472. }
  39473. else if (parsedGeometry instanceof ArrayBuffer) {
  39474. var binaryInfo = mesh._binaryInfo;
  39475. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39476. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39477. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39478. }
  39479. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39480. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39481. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39482. }
  39483. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39484. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39486. }
  39487. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39488. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39489. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39490. }
  39491. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39492. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39493. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39494. }
  39495. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39496. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39497. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39498. }
  39499. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39500. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39502. }
  39503. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39504. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39505. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39506. }
  39507. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39508. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39509. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39510. }
  39511. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39512. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39513. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39514. }
  39515. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39516. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39517. var floatIndices = [];
  39518. for (var i = 0; i < matricesIndicesData.length; i++) {
  39519. var index = matricesIndicesData[i];
  39520. floatIndices.push(index & 0x000000FF);
  39521. floatIndices.push((index & 0x0000FF00) >> 8);
  39522. floatIndices.push((index & 0x00FF0000) >> 16);
  39523. floatIndices.push(index >> 24);
  39524. }
  39525. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39526. }
  39527. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39528. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39530. }
  39531. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39532. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39533. mesh.setIndices(indicesData, null);
  39534. }
  39535. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39536. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39537. mesh.subMeshes = [];
  39538. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39539. var materialIndex = subMeshesData[(i * 5) + 0];
  39540. var verticesStart = subMeshesData[(i * 5) + 1];
  39541. var verticesCount = subMeshesData[(i * 5) + 2];
  39542. var indexStart = subMeshesData[(i * 5) + 3];
  39543. var indexCount = subMeshesData[(i * 5) + 4];
  39544. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39545. }
  39546. }
  39547. }
  39548. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39549. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39551. if (parsedGeometry.tangents) {
  39552. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39553. }
  39554. if (parsedGeometry.uvs) {
  39555. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39556. }
  39557. if (parsedGeometry.uvs2) {
  39558. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39559. }
  39560. if (parsedGeometry.uvs3) {
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39562. }
  39563. if (parsedGeometry.uvs4) {
  39564. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39565. }
  39566. if (parsedGeometry.uvs5) {
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39568. }
  39569. if (parsedGeometry.uvs6) {
  39570. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39571. }
  39572. if (parsedGeometry.colors) {
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39574. }
  39575. if (parsedGeometry.matricesIndices) {
  39576. if (!parsedGeometry.matricesIndices._isExpanded) {
  39577. var floatIndices = [];
  39578. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39579. var matricesIndex = parsedGeometry.matricesIndices[i];
  39580. floatIndices.push(matricesIndex & 0x000000FF);
  39581. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39582. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39583. floatIndices.push(matricesIndex >> 24);
  39584. }
  39585. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39586. }
  39587. else {
  39588. delete parsedGeometry.matricesIndices._isExpanded;
  39589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39590. }
  39591. }
  39592. if (parsedGeometry.matricesIndicesExtra) {
  39593. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39594. var floatIndices = [];
  39595. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39596. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39597. floatIndices.push(matricesIndex & 0x000000FF);
  39598. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39599. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39600. floatIndices.push(matricesIndex >> 24);
  39601. }
  39602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39603. }
  39604. else {
  39605. delete parsedGeometry.matricesIndices._isExpanded;
  39606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39607. }
  39608. }
  39609. if (parsedGeometry.matricesWeights) {
  39610. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39612. }
  39613. if (parsedGeometry.matricesWeightsExtra) {
  39614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39615. }
  39616. mesh.setIndices(parsedGeometry.indices, null);
  39617. }
  39618. // SubMeshes
  39619. if (parsedGeometry.subMeshes) {
  39620. mesh.subMeshes = [];
  39621. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39622. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39623. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39624. }
  39625. }
  39626. // Flat shading
  39627. if (mesh._shouldGenerateFlatShading) {
  39628. mesh.convertToFlatShadedMesh();
  39629. delete mesh._shouldGenerateFlatShading;
  39630. }
  39631. // Update
  39632. mesh.computeWorldMatrix(true);
  39633. // Octree
  39634. var sceneOctree = scene.selectionOctree;
  39635. if (sceneOctree !== undefined && sceneOctree !== null) {
  39636. sceneOctree.addMesh(mesh);
  39637. }
  39638. };
  39639. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39640. var epsilon = 1e-3;
  39641. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39642. return;
  39643. }
  39644. var noInfluenceBoneIndex = 0.0;
  39645. if (parsedGeometry.skeletonId > -1) {
  39646. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39647. if (!skeleton) {
  39648. return;
  39649. }
  39650. noInfluenceBoneIndex = skeleton.bones.length;
  39651. }
  39652. else {
  39653. return;
  39654. }
  39655. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39656. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39657. var matricesWeights = parsedGeometry.matricesWeights;
  39658. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39659. var influencers = parsedGeometry.numBoneInfluencer;
  39660. var size = matricesWeights.length;
  39661. for (var i = 0; i < size; i += 4) {
  39662. var weight = 0.0;
  39663. var firstZeroWeight = -1;
  39664. for (var j = 0; j < 4; j++) {
  39665. var w = matricesWeights[i + j];
  39666. weight += w;
  39667. if (w < epsilon && firstZeroWeight < 0) {
  39668. firstZeroWeight = j;
  39669. }
  39670. }
  39671. if (matricesWeightsExtra) {
  39672. for (var j = 0; j < 4; j++) {
  39673. var w = matricesWeightsExtra[i + j];
  39674. weight += w;
  39675. if (w < epsilon && firstZeroWeight < 0) {
  39676. firstZeroWeight = j + 4;
  39677. }
  39678. }
  39679. }
  39680. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39681. firstZeroWeight = influencers - 1;
  39682. }
  39683. if (weight > epsilon) {
  39684. var mweight = 1.0 / weight;
  39685. for (var j = 0; j < 4; j++) {
  39686. matricesWeights[i + j] *= mweight;
  39687. }
  39688. if (matricesWeightsExtra) {
  39689. for (var j = 0; j < 4; j++) {
  39690. matricesWeightsExtra[i + j] *= mweight;
  39691. }
  39692. }
  39693. }
  39694. else {
  39695. if (firstZeroWeight >= 4) {
  39696. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39697. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39698. }
  39699. else {
  39700. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39701. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39702. }
  39703. }
  39704. }
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39706. if (parsedGeometry.matricesWeightsExtra) {
  39707. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39708. }
  39709. };
  39710. /**
  39711. * Create a new geometry from persisted data (Using .babylon file format)
  39712. * @param parsedVertexData defines the persisted data
  39713. * @param scene defines the hosting scene
  39714. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39715. * @returns the new geometry object
  39716. */
  39717. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39718. if (scene.getGeometryByID(parsedVertexData.id)) {
  39719. return null; // null since geometry could be something else than a box...
  39720. }
  39721. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39722. if (BABYLON.Tags) {
  39723. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39724. }
  39725. if (parsedVertexData.delayLoadingFile) {
  39726. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39727. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39728. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39729. geometry._delayInfo = [];
  39730. if (parsedVertexData.hasUVs) {
  39731. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39732. }
  39733. if (parsedVertexData.hasUVs2) {
  39734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39735. }
  39736. if (parsedVertexData.hasUVs3) {
  39737. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39738. }
  39739. if (parsedVertexData.hasUVs4) {
  39740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39741. }
  39742. if (parsedVertexData.hasUVs5) {
  39743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39744. }
  39745. if (parsedVertexData.hasUVs6) {
  39746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39747. }
  39748. if (parsedVertexData.hasColors) {
  39749. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39750. }
  39751. if (parsedVertexData.hasMatricesIndices) {
  39752. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39753. }
  39754. if (parsedVertexData.hasMatricesWeights) {
  39755. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39756. }
  39757. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39758. }
  39759. else {
  39760. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39761. }
  39762. scene.pushGeometry(geometry, true);
  39763. return geometry;
  39764. };
  39765. return Geometry;
  39766. }());
  39767. BABYLON.Geometry = Geometry;
  39768. // Primitives
  39769. /// Abstract class
  39770. /**
  39771. * Abstract class used to provide common services for all typed geometries
  39772. * @hidden
  39773. */
  39774. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39775. __extends(_PrimitiveGeometry, _super);
  39776. /**
  39777. * Creates a new typed geometry
  39778. * @param id defines the unique ID of the geometry
  39779. * @param scene defines the hosting scene
  39780. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39781. * @param mesh defines the hosting mesh (can be null)
  39782. */
  39783. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39784. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39785. if (mesh === void 0) { mesh = null; }
  39786. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39787. _this._canBeRegenerated = _canBeRegenerated;
  39788. _this._beingRegenerated = true;
  39789. _this.regenerate();
  39790. _this._beingRegenerated = false;
  39791. return _this;
  39792. }
  39793. /**
  39794. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39795. * @returns true if the geometry can be regenerated
  39796. */
  39797. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39798. return this._canBeRegenerated;
  39799. };
  39800. /**
  39801. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39802. */
  39803. _PrimitiveGeometry.prototype.regenerate = function () {
  39804. if (!this._canBeRegenerated) {
  39805. return;
  39806. }
  39807. this._beingRegenerated = true;
  39808. this.setAllVerticesData(this._regenerateVertexData(), false);
  39809. this._beingRegenerated = false;
  39810. };
  39811. /**
  39812. * Clone the geometry
  39813. * @param id defines the unique ID of the new geometry
  39814. * @returns the new geometry
  39815. */
  39816. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39817. return _super.prototype.copy.call(this, id);
  39818. };
  39819. // overrides
  39820. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39821. if (!this._beingRegenerated) {
  39822. return;
  39823. }
  39824. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39825. };
  39826. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39827. if (!this._beingRegenerated) {
  39828. return;
  39829. }
  39830. _super.prototype.setVerticesData.call(this, kind, data, false);
  39831. };
  39832. // to override
  39833. /** @hidden */
  39834. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39835. throw new Error("Abstract method");
  39836. };
  39837. _PrimitiveGeometry.prototype.copy = function (id) {
  39838. throw new Error("Must be overriden in sub-classes.");
  39839. };
  39840. _PrimitiveGeometry.prototype.serialize = function () {
  39841. var serializationObject = _super.prototype.serialize.call(this);
  39842. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39843. return serializationObject;
  39844. };
  39845. return _PrimitiveGeometry;
  39846. }(Geometry));
  39847. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39848. /**
  39849. * Creates a ribbon geometry
  39850. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39851. */
  39852. var RibbonGeometry = /** @class */ (function (_super) {
  39853. __extends(RibbonGeometry, _super);
  39854. /**
  39855. * Creates a ribbon geometry
  39856. * @param id defines the unique ID of the geometry
  39857. * @param scene defines the hosting scene
  39858. * @param pathArray defines the array of paths to use
  39859. * @param closeArray defines if the last path and the first path must be joined
  39860. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39861. * @param offset defines the offset between points
  39862. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39863. * @param mesh defines the hosting mesh (can be null)
  39864. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39865. */
  39866. function RibbonGeometry(id, scene,
  39867. /**
  39868. * Defines the array of paths to use
  39869. */
  39870. pathArray,
  39871. /**
  39872. * Defines if the last and first points of each path in your pathArray must be joined
  39873. */
  39874. closeArray,
  39875. /**
  39876. * Defines if the last and first points of each path in your pathArray must be joined
  39877. */
  39878. closePath,
  39879. /**
  39880. * Defines the offset between points
  39881. */
  39882. offset, canBeRegenerated, mesh,
  39883. /**
  39884. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39885. */
  39886. side) {
  39887. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39888. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39889. _this.pathArray = pathArray;
  39890. _this.closeArray = closeArray;
  39891. _this.closePath = closePath;
  39892. _this.offset = offset;
  39893. _this.side = side;
  39894. return _this;
  39895. }
  39896. /** @hidden */
  39897. RibbonGeometry.prototype._regenerateVertexData = function () {
  39898. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39899. };
  39900. RibbonGeometry.prototype.copy = function (id) {
  39901. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39902. };
  39903. return RibbonGeometry;
  39904. }(_PrimitiveGeometry));
  39905. BABYLON.RibbonGeometry = RibbonGeometry;
  39906. /**
  39907. * Creates a box geometry
  39908. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39909. */
  39910. var BoxGeometry = /** @class */ (function (_super) {
  39911. __extends(BoxGeometry, _super);
  39912. /**
  39913. * Creates a box geometry
  39914. * @param id defines the unique ID of the geometry
  39915. * @param scene defines the hosting scene
  39916. * @param size defines the zise of the box (width, height and depth are the same)
  39917. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39918. * @param mesh defines the hosting mesh (can be null)
  39919. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39920. */
  39921. function BoxGeometry(id, scene,
  39922. /**
  39923. * Defines the zise of the box (width, height and depth are the same)
  39924. */
  39925. size, canBeRegenerated, mesh,
  39926. /**
  39927. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39928. */
  39929. side) {
  39930. if (mesh === void 0) { mesh = null; }
  39931. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39932. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39933. _this.size = size;
  39934. _this.side = side;
  39935. return _this;
  39936. }
  39937. BoxGeometry.prototype._regenerateVertexData = function () {
  39938. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39939. };
  39940. BoxGeometry.prototype.copy = function (id) {
  39941. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39942. };
  39943. BoxGeometry.prototype.serialize = function () {
  39944. var serializationObject = _super.prototype.serialize.call(this);
  39945. serializationObject.size = this.size;
  39946. return serializationObject;
  39947. };
  39948. BoxGeometry.Parse = function (parsedBox, scene) {
  39949. if (scene.getGeometryByID(parsedBox.id)) {
  39950. return null; // null since geometry could be something else than a box...
  39951. }
  39952. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39953. if (BABYLON.Tags) {
  39954. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39955. }
  39956. scene.pushGeometry(box, true);
  39957. return box;
  39958. };
  39959. return BoxGeometry;
  39960. }(_PrimitiveGeometry));
  39961. BABYLON.BoxGeometry = BoxGeometry;
  39962. /**
  39963. * Creates a sphere geometry
  39964. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39965. */
  39966. var SphereGeometry = /** @class */ (function (_super) {
  39967. __extends(SphereGeometry, _super);
  39968. /**
  39969. * Create a new sphere geometry
  39970. * @param id defines the unique ID of the geometry
  39971. * @param scene defines the hosting scene
  39972. * @param segments defines the number of segments to use to create the sphere
  39973. * @param diameter defines the diameter of the sphere
  39974. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39975. * @param mesh defines the hosting mesh (can be null)
  39976. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39977. */
  39978. function SphereGeometry(id, scene,
  39979. /**
  39980. * Defines the number of segments to use to create the sphere
  39981. */
  39982. segments,
  39983. /**
  39984. * Defines the diameter of the sphere
  39985. */
  39986. diameter, canBeRegenerated, mesh,
  39987. /**
  39988. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39989. */
  39990. side) {
  39991. if (mesh === void 0) { mesh = null; }
  39992. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39993. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39994. _this.segments = segments;
  39995. _this.diameter = diameter;
  39996. _this.side = side;
  39997. return _this;
  39998. }
  39999. SphereGeometry.prototype._regenerateVertexData = function () {
  40000. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40001. };
  40002. SphereGeometry.prototype.copy = function (id) {
  40003. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40004. };
  40005. SphereGeometry.prototype.serialize = function () {
  40006. var serializationObject = _super.prototype.serialize.call(this);
  40007. serializationObject.segments = this.segments;
  40008. serializationObject.diameter = this.diameter;
  40009. return serializationObject;
  40010. };
  40011. SphereGeometry.Parse = function (parsedSphere, scene) {
  40012. if (scene.getGeometryByID(parsedSphere.id)) {
  40013. return null; // null since geometry could be something else than a sphere...
  40014. }
  40015. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40016. if (BABYLON.Tags) {
  40017. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40018. }
  40019. scene.pushGeometry(sphere, true);
  40020. return sphere;
  40021. };
  40022. return SphereGeometry;
  40023. }(_PrimitiveGeometry));
  40024. BABYLON.SphereGeometry = SphereGeometry;
  40025. /**
  40026. * Creates a disc geometry
  40027. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40028. */
  40029. var DiscGeometry = /** @class */ (function (_super) {
  40030. __extends(DiscGeometry, _super);
  40031. /**
  40032. * Creates a new disc geometry
  40033. * @param id defines the unique ID of the geometry
  40034. * @param scene defines the hosting scene
  40035. * @param radius defines the radius of the disc
  40036. * @param tessellation defines the tesselation factor to apply to the disc
  40037. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40038. * @param mesh defines the hosting mesh (can be null)
  40039. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40040. */
  40041. function DiscGeometry(id, scene,
  40042. /**
  40043. * Defines the radius of the disc
  40044. */
  40045. radius,
  40046. /**
  40047. * Defines the tesselation factor to apply to the disc
  40048. */
  40049. tessellation, canBeRegenerated, mesh,
  40050. /**
  40051. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40052. */
  40053. side) {
  40054. if (mesh === void 0) { mesh = null; }
  40055. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40056. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40057. _this.radius = radius;
  40058. _this.tessellation = tessellation;
  40059. _this.side = side;
  40060. return _this;
  40061. }
  40062. DiscGeometry.prototype._regenerateVertexData = function () {
  40063. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40064. };
  40065. DiscGeometry.prototype.copy = function (id) {
  40066. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40067. };
  40068. return DiscGeometry;
  40069. }(_PrimitiveGeometry));
  40070. BABYLON.DiscGeometry = DiscGeometry;
  40071. /**
  40072. * Creates a new cylinder geometry
  40073. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40074. */
  40075. var CylinderGeometry = /** @class */ (function (_super) {
  40076. __extends(CylinderGeometry, _super);
  40077. /**
  40078. * Creates a new cylinder geometry
  40079. * @param id defines the unique ID of the geometry
  40080. * @param scene defines the hosting scene
  40081. * @param height defines the height of the cylinder
  40082. * @param diameterTop defines the diameter of the cylinder's top cap
  40083. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40084. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40085. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40086. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40087. * @param mesh defines the hosting mesh (can be null)
  40088. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40089. */
  40090. function CylinderGeometry(id, scene,
  40091. /**
  40092. * Defines the height of the cylinder
  40093. */
  40094. height,
  40095. /**
  40096. * Defines the diameter of the cylinder's top cap
  40097. */
  40098. diameterTop,
  40099. /**
  40100. * Defines the diameter of the cylinder's bottom cap
  40101. */
  40102. diameterBottom,
  40103. /**
  40104. * Defines the tessellation factor to apply to the cylinder
  40105. */
  40106. tessellation,
  40107. /**
  40108. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40109. */
  40110. subdivisions, canBeRegenerated, mesh,
  40111. /**
  40112. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40113. */
  40114. side) {
  40115. if (subdivisions === void 0) { subdivisions = 1; }
  40116. if (mesh === void 0) { mesh = null; }
  40117. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40118. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40119. _this.height = height;
  40120. _this.diameterTop = diameterTop;
  40121. _this.diameterBottom = diameterBottom;
  40122. _this.tessellation = tessellation;
  40123. _this.subdivisions = subdivisions;
  40124. _this.side = side;
  40125. return _this;
  40126. }
  40127. CylinderGeometry.prototype._regenerateVertexData = function () {
  40128. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40129. };
  40130. CylinderGeometry.prototype.copy = function (id) {
  40131. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40132. };
  40133. CylinderGeometry.prototype.serialize = function () {
  40134. var serializationObject = _super.prototype.serialize.call(this);
  40135. serializationObject.height = this.height;
  40136. serializationObject.diameterTop = this.diameterTop;
  40137. serializationObject.diameterBottom = this.diameterBottom;
  40138. serializationObject.tessellation = this.tessellation;
  40139. return serializationObject;
  40140. };
  40141. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40142. if (scene.getGeometryByID(parsedCylinder.id)) {
  40143. return null; // null since geometry could be something else than a cylinder...
  40144. }
  40145. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40146. if (BABYLON.Tags) {
  40147. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40148. }
  40149. scene.pushGeometry(cylinder, true);
  40150. return cylinder;
  40151. };
  40152. return CylinderGeometry;
  40153. }(_PrimitiveGeometry));
  40154. BABYLON.CylinderGeometry = CylinderGeometry;
  40155. /**
  40156. * Creates a new torus geometry
  40157. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40158. */
  40159. var TorusGeometry = /** @class */ (function (_super) {
  40160. __extends(TorusGeometry, _super);
  40161. /**
  40162. * Creates a new torus geometry
  40163. * @param id defines the unique ID of the geometry
  40164. * @param scene defines the hosting scene
  40165. * @param diameter defines the diameter of the torus
  40166. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40167. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40168. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40169. * @param mesh defines the hosting mesh (can be null)
  40170. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40171. */
  40172. function TorusGeometry(id, scene,
  40173. /**
  40174. * Defines the diameter of the torus
  40175. */
  40176. diameter,
  40177. /**
  40178. * Defines the thickness of the torus (ie. internal diameter)
  40179. */
  40180. thickness,
  40181. /**
  40182. * Defines the tesselation factor to apply to the torus
  40183. */
  40184. tessellation, canBeRegenerated, mesh,
  40185. /**
  40186. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40187. */
  40188. side) {
  40189. if (mesh === void 0) { mesh = null; }
  40190. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40191. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40192. _this.diameter = diameter;
  40193. _this.thickness = thickness;
  40194. _this.tessellation = tessellation;
  40195. _this.side = side;
  40196. return _this;
  40197. }
  40198. TorusGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40200. };
  40201. TorusGeometry.prototype.copy = function (id) {
  40202. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40203. };
  40204. TorusGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.diameter = this.diameter;
  40207. serializationObject.thickness = this.thickness;
  40208. serializationObject.tessellation = this.tessellation;
  40209. return serializationObject;
  40210. };
  40211. TorusGeometry.Parse = function (parsedTorus, scene) {
  40212. if (scene.getGeometryByID(parsedTorus.id)) {
  40213. return null; // null since geometry could be something else than a torus...
  40214. }
  40215. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40216. if (BABYLON.Tags) {
  40217. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40218. }
  40219. scene.pushGeometry(torus, true);
  40220. return torus;
  40221. };
  40222. return TorusGeometry;
  40223. }(_PrimitiveGeometry));
  40224. BABYLON.TorusGeometry = TorusGeometry;
  40225. /**
  40226. * Creates a new ground geometry
  40227. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40228. */
  40229. var GroundGeometry = /** @class */ (function (_super) {
  40230. __extends(GroundGeometry, _super);
  40231. /**
  40232. * Creates a new ground geometry
  40233. * @param id defines the unique ID of the geometry
  40234. * @param scene defines the hosting scene
  40235. * @param width defines the width of the ground
  40236. * @param height defines the height of the ground
  40237. * @param subdivisions defines the subdivisions to apply to the ground
  40238. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40239. * @param mesh defines the hosting mesh (can be null)
  40240. */
  40241. function GroundGeometry(id, scene,
  40242. /**
  40243. * Defines the width of the ground
  40244. */
  40245. width,
  40246. /**
  40247. * Defines the height of the ground
  40248. */
  40249. height,
  40250. /**
  40251. * Defines the subdivisions to apply to the ground
  40252. */
  40253. subdivisions, canBeRegenerated, mesh) {
  40254. if (mesh === void 0) { mesh = null; }
  40255. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40256. _this.width = width;
  40257. _this.height = height;
  40258. _this.subdivisions = subdivisions;
  40259. return _this;
  40260. }
  40261. GroundGeometry.prototype._regenerateVertexData = function () {
  40262. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40263. };
  40264. GroundGeometry.prototype.copy = function (id) {
  40265. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40266. };
  40267. GroundGeometry.prototype.serialize = function () {
  40268. var serializationObject = _super.prototype.serialize.call(this);
  40269. serializationObject.width = this.width;
  40270. serializationObject.height = this.height;
  40271. serializationObject.subdivisions = this.subdivisions;
  40272. return serializationObject;
  40273. };
  40274. GroundGeometry.Parse = function (parsedGround, scene) {
  40275. if (scene.getGeometryByID(parsedGround.id)) {
  40276. return null; // null since geometry could be something else than a ground...
  40277. }
  40278. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40279. if (BABYLON.Tags) {
  40280. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40281. }
  40282. scene.pushGeometry(ground, true);
  40283. return ground;
  40284. };
  40285. return GroundGeometry;
  40286. }(_PrimitiveGeometry));
  40287. BABYLON.GroundGeometry = GroundGeometry;
  40288. /**
  40289. * Creates a tiled ground geometry
  40290. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40291. */
  40292. var TiledGroundGeometry = /** @class */ (function (_super) {
  40293. __extends(TiledGroundGeometry, _super);
  40294. /**
  40295. * Creates a tiled ground geometry
  40296. * @param id defines the unique ID of the geometry
  40297. * @param scene defines the hosting scene
  40298. * @param xmin defines the minimum value on X axis
  40299. * @param zmin defines the minimum value on Z axis
  40300. * @param xmax defines the maximum value on X axis
  40301. * @param zmax defines the maximum value on Z axis
  40302. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40303. * @param precision defines the precision to use when computing the tiles
  40304. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40305. * @param mesh defines the hosting mesh (can be null)
  40306. */
  40307. function TiledGroundGeometry(id, scene,
  40308. /**
  40309. * Defines the minimum value on X axis
  40310. */
  40311. xmin,
  40312. /**
  40313. * Defines the minimum value on Z axis
  40314. */
  40315. zmin,
  40316. /**
  40317. * Defines the maximum value on X axis
  40318. */
  40319. xmax,
  40320. /**
  40321. * Defines the maximum value on Z axis
  40322. */
  40323. zmax,
  40324. /**
  40325. * Defines the subdivisions to apply to the ground
  40326. */
  40327. subdivisions,
  40328. /**
  40329. * Defines the precision to use when computing the tiles
  40330. */
  40331. precision, canBeRegenerated, mesh) {
  40332. if (mesh === void 0) { mesh = null; }
  40333. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40334. _this.xmin = xmin;
  40335. _this.zmin = zmin;
  40336. _this.xmax = xmax;
  40337. _this.zmax = zmax;
  40338. _this.subdivisions = subdivisions;
  40339. _this.precision = precision;
  40340. return _this;
  40341. }
  40342. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40343. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40344. };
  40345. TiledGroundGeometry.prototype.copy = function (id) {
  40346. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40347. };
  40348. return TiledGroundGeometry;
  40349. }(_PrimitiveGeometry));
  40350. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40351. /**
  40352. * Creates a plane geometry
  40353. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40354. */
  40355. var PlaneGeometry = /** @class */ (function (_super) {
  40356. __extends(PlaneGeometry, _super);
  40357. /**
  40358. * Creates a plane geometry
  40359. * @param id defines the unique ID of the geometry
  40360. * @param scene defines the hosting scene
  40361. * @param size defines the size of the plane (width === height)
  40362. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40363. * @param mesh defines the hosting mesh (can be null)
  40364. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40365. */
  40366. function PlaneGeometry(id, scene,
  40367. /**
  40368. * Defines the size of the plane (width === height)
  40369. */
  40370. size, canBeRegenerated, mesh,
  40371. /**
  40372. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40373. */
  40374. side) {
  40375. if (mesh === void 0) { mesh = null; }
  40376. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40377. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40378. _this.size = size;
  40379. _this.side = side;
  40380. return _this;
  40381. }
  40382. PlaneGeometry.prototype._regenerateVertexData = function () {
  40383. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40384. };
  40385. PlaneGeometry.prototype.copy = function (id) {
  40386. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40387. };
  40388. PlaneGeometry.prototype.serialize = function () {
  40389. var serializationObject = _super.prototype.serialize.call(this);
  40390. serializationObject.size = this.size;
  40391. return serializationObject;
  40392. };
  40393. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40394. if (scene.getGeometryByID(parsedPlane.id)) {
  40395. return null; // null since geometry could be something else than a ground...
  40396. }
  40397. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40398. if (BABYLON.Tags) {
  40399. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40400. }
  40401. scene.pushGeometry(plane, true);
  40402. return plane;
  40403. };
  40404. return PlaneGeometry;
  40405. }(_PrimitiveGeometry));
  40406. BABYLON.PlaneGeometry = PlaneGeometry;
  40407. /**
  40408. * Creates a torus knot geometry
  40409. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40410. */
  40411. var TorusKnotGeometry = /** @class */ (function (_super) {
  40412. __extends(TorusKnotGeometry, _super);
  40413. /**
  40414. * Creates a torus knot geometry
  40415. * @param id defines the unique ID of the geometry
  40416. * @param scene defines the hosting scene
  40417. * @param radius defines the radius of the torus knot
  40418. * @param tube defines the thickness of the torus knot tube
  40419. * @param radialSegments defines the number of radial segments
  40420. * @param tubularSegments defines the number of tubular segments
  40421. * @param p defines the first number of windings
  40422. * @param q defines the second number of windings
  40423. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40424. * @param mesh defines the hosting mesh (can be null)
  40425. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40426. */
  40427. function TorusKnotGeometry(id, scene,
  40428. /**
  40429. * Defines the radius of the torus knot
  40430. */
  40431. radius,
  40432. /**
  40433. * Defines the thickness of the torus knot tube
  40434. */
  40435. tube,
  40436. /**
  40437. * Defines the number of radial segments
  40438. */
  40439. radialSegments,
  40440. /**
  40441. * Defines the number of tubular segments
  40442. */
  40443. tubularSegments,
  40444. /**
  40445. * Defines the first number of windings
  40446. */
  40447. p,
  40448. /**
  40449. * Defines the second number of windings
  40450. */
  40451. q, canBeRegenerated, mesh,
  40452. /**
  40453. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40454. */
  40455. side) {
  40456. if (mesh === void 0) { mesh = null; }
  40457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40459. _this.radius = radius;
  40460. _this.tube = tube;
  40461. _this.radialSegments = radialSegments;
  40462. _this.tubularSegments = tubularSegments;
  40463. _this.p = p;
  40464. _this.q = q;
  40465. _this.side = side;
  40466. return _this;
  40467. }
  40468. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40469. 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 });
  40470. };
  40471. TorusKnotGeometry.prototype.copy = function (id) {
  40472. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40473. };
  40474. TorusKnotGeometry.prototype.serialize = function () {
  40475. var serializationObject = _super.prototype.serialize.call(this);
  40476. serializationObject.radius = this.radius;
  40477. serializationObject.tube = this.tube;
  40478. serializationObject.radialSegments = this.radialSegments;
  40479. serializationObject.tubularSegments = this.tubularSegments;
  40480. serializationObject.p = this.p;
  40481. serializationObject.q = this.q;
  40482. return serializationObject;
  40483. };
  40484. ;
  40485. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40486. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40487. return null; // null since geometry could be something else than a ground...
  40488. }
  40489. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40490. if (BABYLON.Tags) {
  40491. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40492. }
  40493. scene.pushGeometry(torusKnot, true);
  40494. return torusKnot;
  40495. };
  40496. return TorusKnotGeometry;
  40497. }(_PrimitiveGeometry));
  40498. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40499. //}
  40500. })(BABYLON || (BABYLON = {}));
  40501. //# sourceMappingURL=babylon.geometry.js.map
  40502. var BABYLON;
  40503. (function (BABYLON) {
  40504. /**
  40505. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40506. */
  40507. var PerformanceMonitor = /** @class */ (function () {
  40508. /**
  40509. * constructor
  40510. * @param frameSampleSize The number of samples required to saturate the sliding window
  40511. */
  40512. function PerformanceMonitor(frameSampleSize) {
  40513. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40514. this._enabled = true;
  40515. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40516. }
  40517. /**
  40518. * Samples current frame
  40519. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40520. */
  40521. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40522. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40523. if (!this._enabled)
  40524. return;
  40525. if (this._lastFrameTimeMs != null) {
  40526. var dt = timeMs - this._lastFrameTimeMs;
  40527. this._rollingFrameTime.add(dt);
  40528. }
  40529. this._lastFrameTimeMs = timeMs;
  40530. };
  40531. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40532. /**
  40533. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40534. * @return Average frame time in milliseconds
  40535. */
  40536. get: function () {
  40537. return this._rollingFrameTime.average;
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40543. /**
  40544. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40545. * @return Frame time variance in milliseconds squared
  40546. */
  40547. get: function () {
  40548. return this._rollingFrameTime.variance;
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40554. /**
  40555. * Returns the frame time of the most recent frame
  40556. * @return Frame time in milliseconds
  40557. */
  40558. get: function () {
  40559. return this._rollingFrameTime.history(0);
  40560. },
  40561. enumerable: true,
  40562. configurable: true
  40563. });
  40564. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40565. /**
  40566. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40567. * @return Framerate in frames per second
  40568. */
  40569. get: function () {
  40570. return 1000.0 / this._rollingFrameTime.average;
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40576. /**
  40577. * Returns the average framerate in frames per second using the most recent frame time
  40578. * @return Framerate in frames per second
  40579. */
  40580. get: function () {
  40581. var history = this._rollingFrameTime.history(0);
  40582. if (history === 0) {
  40583. return 0;
  40584. }
  40585. return 1000.0 / history;
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40591. /**
  40592. * Returns true if enough samples have been taken to completely fill the sliding window
  40593. * @return true if saturated
  40594. */
  40595. get: function () {
  40596. return this._rollingFrameTime.isSaturated();
  40597. },
  40598. enumerable: true,
  40599. configurable: true
  40600. });
  40601. /**
  40602. * Enables contributions to the sliding window sample set
  40603. */
  40604. PerformanceMonitor.prototype.enable = function () {
  40605. this._enabled = true;
  40606. };
  40607. /**
  40608. * Disables contributions to the sliding window sample set
  40609. * Samples will not be interpolated over the disabled period
  40610. */
  40611. PerformanceMonitor.prototype.disable = function () {
  40612. this._enabled = false;
  40613. //clear last sample to avoid interpolating over the disabled period when next enabled
  40614. this._lastFrameTimeMs = null;
  40615. };
  40616. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40617. /**
  40618. * Returns true if sampling is enabled
  40619. * @return true if enabled
  40620. */
  40621. get: function () {
  40622. return this._enabled;
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. /**
  40628. * Resets performance monitor
  40629. */
  40630. PerformanceMonitor.prototype.reset = function () {
  40631. //clear last sample to avoid interpolating over the disabled period when next enabled
  40632. this._lastFrameTimeMs = null;
  40633. //wipe record
  40634. this._rollingFrameTime.reset();
  40635. };
  40636. return PerformanceMonitor;
  40637. }());
  40638. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40639. /**
  40640. * RollingAverage
  40641. *
  40642. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40643. */
  40644. var RollingAverage = /** @class */ (function () {
  40645. /**
  40646. * constructor
  40647. * @param length The number of samples required to saturate the sliding window
  40648. */
  40649. function RollingAverage(length) {
  40650. this._samples = new Array(length);
  40651. this.reset();
  40652. }
  40653. /**
  40654. * Adds a sample to the sample set
  40655. * @param v The sample value
  40656. */
  40657. RollingAverage.prototype.add = function (v) {
  40658. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40659. var delta;
  40660. //we need to check if we've already wrapped round
  40661. if (this.isSaturated()) {
  40662. //remove bottom of stack from mean
  40663. var bottomValue = this._samples[this._pos];
  40664. delta = bottomValue - this.average;
  40665. this.average -= delta / (this._sampleCount - 1);
  40666. this._m2 -= delta * (bottomValue - this.average);
  40667. }
  40668. else {
  40669. this._sampleCount++;
  40670. }
  40671. //add new value to mean
  40672. delta = v - this.average;
  40673. this.average += delta / (this._sampleCount);
  40674. this._m2 += delta * (v - this.average);
  40675. //set the new variance
  40676. this.variance = this._m2 / (this._sampleCount - 1);
  40677. this._samples[this._pos] = v;
  40678. this._pos++;
  40679. this._pos %= this._samples.length; //positive wrap around
  40680. };
  40681. /**
  40682. * Returns previously added values or null if outside of history or outside the sliding window domain
  40683. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40684. * @return Value previously recorded with add() or null if outside of range
  40685. */
  40686. RollingAverage.prototype.history = function (i) {
  40687. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40688. return 0;
  40689. }
  40690. var i0 = this._wrapPosition(this._pos - 1.0);
  40691. return this._samples[this._wrapPosition(i0 - i)];
  40692. };
  40693. /**
  40694. * Returns true if enough samples have been taken to completely fill the sliding window
  40695. * @return true if sample-set saturated
  40696. */
  40697. RollingAverage.prototype.isSaturated = function () {
  40698. return this._sampleCount >= this._samples.length;
  40699. };
  40700. /**
  40701. * Resets the rolling average (equivalent to 0 samples taken so far)
  40702. */
  40703. RollingAverage.prototype.reset = function () {
  40704. this.average = 0;
  40705. this.variance = 0;
  40706. this._sampleCount = 0;
  40707. this._pos = 0;
  40708. this._m2 = 0;
  40709. };
  40710. /**
  40711. * Wraps a value around the sample range boundaries
  40712. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40713. * @return Wrapped position in sample range
  40714. */
  40715. RollingAverage.prototype._wrapPosition = function (i) {
  40716. var max = this._samples.length;
  40717. return ((i % max) + max) % max;
  40718. };
  40719. return RollingAverage;
  40720. }());
  40721. BABYLON.RollingAverage = RollingAverage;
  40722. })(BABYLON || (BABYLON = {}));
  40723. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40724. var BABYLON;
  40725. (function (BABYLON) {
  40726. /**
  40727. * "Static Class" containing the most commonly used helper while dealing with material for
  40728. * rendering purpose.
  40729. *
  40730. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40731. *
  40732. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40733. */
  40734. var MaterialHelper = /** @class */ (function () {
  40735. function MaterialHelper() {
  40736. }
  40737. /**
  40738. * Bind the current view position to an effect.
  40739. * @param effect The effect to be bound
  40740. * @param scene The scene the eyes position is used from
  40741. */
  40742. MaterialHelper.BindEyePosition = function (effect, scene) {
  40743. if (scene._forcedViewPosition) {
  40744. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40745. return;
  40746. }
  40747. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40748. };
  40749. /**
  40750. * Helps preparing the defines values about the UVs in used in the effect.
  40751. * UVs are shared as much as we can accross chanels in the shaders.
  40752. * @param texture The texture we are preparing the UVs for
  40753. * @param defines The defines to update
  40754. * @param key The chanel key "diffuse", "specular"... used in the shader
  40755. */
  40756. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40757. defines._needUVs = true;
  40758. defines[key] = true;
  40759. if (texture.getTextureMatrix().isIdentity(true)) {
  40760. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40761. if (texture.coordinatesIndex === 0) {
  40762. defines["MAINUV1"] = true;
  40763. }
  40764. else {
  40765. defines["MAINUV2"] = true;
  40766. }
  40767. }
  40768. else {
  40769. defines[key + "DIRECTUV"] = 0;
  40770. }
  40771. };
  40772. /**
  40773. * Binds a texture matrix value to its corrsponding uniform
  40774. * @param texture The texture to bind the matrix for
  40775. * @param uniformBuffer The uniform buffer receivin the data
  40776. * @param key The chanel key "diffuse", "specular"... used in the shader
  40777. */
  40778. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40779. var matrix = texture.getTextureMatrix();
  40780. if (!matrix.isIdentity(true)) {
  40781. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40782. }
  40783. };
  40784. /**
  40785. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40786. * @param mesh defines the current mesh
  40787. * @param scene defines the current scene
  40788. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40789. * @param pointsCloud defines if point cloud rendering has to be turned on
  40790. * @param fogEnabled defines if fog has to be turned on
  40791. * @param alphaTest defines if alpha testing has to be turned on
  40792. * @param defines defines the current list of defines
  40793. */
  40794. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40795. if (defines._areMiscDirty) {
  40796. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40797. defines["POINTSIZE"] = pointsCloud;
  40798. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40799. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40800. defines["ALPHATEST"] = alphaTest;
  40801. }
  40802. };
  40803. /**
  40804. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40805. * @param scene defines the current scene
  40806. * @param engine defines the current engine
  40807. * @param defines specifies the list of active defines
  40808. * @param useInstances defines if instances have to be turned on
  40809. * @param useClipPlane defines if clip plane have to be turned on
  40810. */
  40811. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40812. if (useClipPlane === void 0) { useClipPlane = null; }
  40813. var changed = false;
  40814. if (useClipPlane == null) {
  40815. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40816. }
  40817. if (defines["CLIPPLANE"] !== useClipPlane) {
  40818. defines["CLIPPLANE"] = useClipPlane;
  40819. changed = true;
  40820. }
  40821. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40822. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40823. changed = true;
  40824. }
  40825. if (defines["INSTANCES"] !== useInstances) {
  40826. defines["INSTANCES"] = useInstances;
  40827. changed = true;
  40828. }
  40829. if (changed) {
  40830. defines.markAsUnprocessed();
  40831. }
  40832. };
  40833. /**
  40834. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40835. * @param mesh The mesh containing the geometry data we will draw
  40836. * @param defines The defines to update
  40837. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40838. * @param useBones Precise whether bones should be used or not (override mesh info)
  40839. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40840. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40841. * @returns false if defines are considered not dirty and have not been checked
  40842. */
  40843. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40844. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40845. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40846. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40847. return false;
  40848. }
  40849. defines._normals = defines._needNormals;
  40850. defines._uvs = defines._needUVs;
  40851. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40852. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40853. defines["TANGENT"] = true;
  40854. }
  40855. if (defines._needUVs) {
  40856. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40857. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40858. }
  40859. else {
  40860. defines["UV1"] = false;
  40861. defines["UV2"] = false;
  40862. }
  40863. if (useVertexColor) {
  40864. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40865. defines["VERTEXCOLOR"] = hasVertexColors;
  40866. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40867. }
  40868. if (useBones) {
  40869. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40870. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40871. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40872. }
  40873. else {
  40874. defines["NUM_BONE_INFLUENCERS"] = 0;
  40875. defines["BonesPerMesh"] = 0;
  40876. }
  40877. }
  40878. if (useMorphTargets) {
  40879. var manager = mesh.morphTargetManager;
  40880. if (manager) {
  40881. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40882. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40883. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40884. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40885. }
  40886. else {
  40887. defines["MORPHTARGETS_TANGENT"] = false;
  40888. defines["MORPHTARGETS_NORMAL"] = false;
  40889. defines["MORPHTARGETS"] = false;
  40890. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40891. }
  40892. }
  40893. return true;
  40894. };
  40895. /**
  40896. * Prepares the defines related to the light information passed in parameter
  40897. * @param scene The scene we are intending to draw
  40898. * @param mesh The mesh the effect is compiling for
  40899. * @param defines The defines to update
  40900. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40901. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40902. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40903. * @returns true if normals will be required for the rest of the effect
  40904. */
  40905. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40906. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40907. if (disableLighting === void 0) { disableLighting = false; }
  40908. if (!defines._areLightsDirty) {
  40909. return defines._needNormals;
  40910. }
  40911. var lightIndex = 0;
  40912. var needNormals = false;
  40913. var needRebuild = false;
  40914. var lightmapMode = false;
  40915. var shadowEnabled = false;
  40916. var specularEnabled = false;
  40917. if (scene.lightsEnabled && !disableLighting) {
  40918. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40919. var light = _a[_i];
  40920. needNormals = true;
  40921. if (defines["LIGHT" + lightIndex] === undefined) {
  40922. needRebuild = true;
  40923. }
  40924. defines["LIGHT" + lightIndex] = true;
  40925. defines["SPOTLIGHT" + lightIndex] = false;
  40926. defines["HEMILIGHT" + lightIndex] = false;
  40927. defines["POINTLIGHT" + lightIndex] = false;
  40928. defines["DIRLIGHT" + lightIndex] = false;
  40929. light.prepareLightSpecificDefines(defines, lightIndex);
  40930. // Specular
  40931. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40932. specularEnabled = true;
  40933. }
  40934. // Shadows
  40935. defines["SHADOW" + lightIndex] = false;
  40936. defines["SHADOWPCF" + lightIndex] = false;
  40937. defines["SHADOWPCSS" + lightIndex] = false;
  40938. defines["SHADOWPOISSON" + lightIndex] = false;
  40939. defines["SHADOWESM" + lightIndex] = false;
  40940. defines["SHADOWCUBE" + lightIndex] = false;
  40941. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40942. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40943. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40944. var shadowGenerator = light.getShadowGenerator();
  40945. if (shadowGenerator) {
  40946. shadowEnabled = true;
  40947. shadowGenerator.prepareDefines(defines, lightIndex);
  40948. }
  40949. }
  40950. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40951. lightmapMode = true;
  40952. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40953. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40954. }
  40955. else {
  40956. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40957. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40958. }
  40959. lightIndex++;
  40960. if (lightIndex === maxSimultaneousLights)
  40961. break;
  40962. }
  40963. }
  40964. defines["SPECULARTERM"] = specularEnabled;
  40965. defines["SHADOWS"] = shadowEnabled;
  40966. // Resetting all other lights if any
  40967. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40968. if (defines["LIGHT" + index] !== undefined) {
  40969. defines["LIGHT" + index] = false;
  40970. defines["HEMILIGHT" + lightIndex] = false;
  40971. defines["POINTLIGHT" + lightIndex] = false;
  40972. defines["DIRLIGHT" + lightIndex] = false;
  40973. defines["SPOTLIGHT" + lightIndex] = false;
  40974. defines["SHADOW" + lightIndex] = false;
  40975. }
  40976. }
  40977. var caps = scene.getEngine().getCaps();
  40978. if (defines["SHADOWFLOAT"] === undefined) {
  40979. needRebuild = true;
  40980. }
  40981. defines["SHADOWFLOAT"] = shadowEnabled &&
  40982. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40983. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40984. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40985. if (needRebuild) {
  40986. defines.rebuild();
  40987. }
  40988. return needNormals;
  40989. };
  40990. /**
  40991. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40992. * that won t be acctive due to defines being turned off.
  40993. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40994. * @param samplersList The samplers list
  40995. * @param defines The defines helping in the list generation
  40996. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40997. */
  40998. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40999. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41000. var uniformsList;
  41001. var uniformBuffersList = null;
  41002. if (uniformsListOrOptions.uniformsNames) {
  41003. var options = uniformsListOrOptions;
  41004. uniformsList = options.uniformsNames;
  41005. uniformBuffersList = options.uniformBuffersNames;
  41006. samplersList = options.samplers;
  41007. defines = options.defines;
  41008. maxSimultaneousLights = options.maxSimultaneousLights;
  41009. }
  41010. else {
  41011. uniformsList = uniformsListOrOptions;
  41012. if (!samplersList) {
  41013. samplersList = [];
  41014. }
  41015. }
  41016. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41017. if (!defines["LIGHT" + lightIndex]) {
  41018. break;
  41019. }
  41020. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41021. if (uniformBuffersList) {
  41022. uniformBuffersList.push("Light" + lightIndex);
  41023. }
  41024. samplersList.push("shadowSampler" + lightIndex);
  41025. samplersList.push("depthSampler" + lightIndex);
  41026. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41027. samplersList.push("projectionLightSampler" + lightIndex);
  41028. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41029. }
  41030. }
  41031. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41032. uniformsList.push("morphTargetInfluences");
  41033. }
  41034. };
  41035. /**
  41036. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41037. * @param defines The defines to update while falling back
  41038. * @param fallbacks The authorized effect fallbacks
  41039. * @param maxSimultaneousLights The maximum number of lights allowed
  41040. * @param rank the current rank of the Effect
  41041. * @returns The newly affected rank
  41042. */
  41043. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41044. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41045. if (rank === void 0) { rank = 0; }
  41046. var lightFallbackRank = 0;
  41047. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41048. if (!defines["LIGHT" + lightIndex]) {
  41049. break;
  41050. }
  41051. if (lightIndex > 0) {
  41052. lightFallbackRank = rank + lightIndex;
  41053. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41054. }
  41055. if (!defines["SHADOWS"]) {
  41056. if (defines["SHADOW" + lightIndex]) {
  41057. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41058. }
  41059. if (defines["SHADOWPCF" + lightIndex]) {
  41060. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41061. }
  41062. if (defines["SHADOWPCSS" + lightIndex]) {
  41063. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41064. }
  41065. if (defines["SHADOWPOISSON" + lightIndex]) {
  41066. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41067. }
  41068. if (defines["SHADOWESM" + lightIndex]) {
  41069. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41070. }
  41071. }
  41072. }
  41073. return lightFallbackRank++;
  41074. };
  41075. /**
  41076. * Prepares the list of attributes required for morph targets according to the effect defines.
  41077. * @param attribs The current list of supported attribs
  41078. * @param mesh The mesh to prepare the morph targets attributes for
  41079. * @param defines The current Defines of the effect
  41080. */
  41081. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41082. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41083. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41084. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41085. var manager = mesh.morphTargetManager;
  41086. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41087. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41088. for (var index = 0; index < influencers; index++) {
  41089. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41090. if (normal) {
  41091. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41092. }
  41093. if (tangent) {
  41094. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41095. }
  41096. if (attribs.length > maxAttributesCount) {
  41097. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41098. }
  41099. }
  41100. }
  41101. };
  41102. /**
  41103. * Prepares the list of attributes required for bones according to the effect defines.
  41104. * @param attribs The current list of supported attribs
  41105. * @param mesh The mesh to prepare the bones attributes for
  41106. * @param defines The current Defines of the effect
  41107. * @param fallbacks The current efffect fallback strategy
  41108. */
  41109. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41110. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41111. fallbacks.addCPUSkinningFallback(0, mesh);
  41112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41114. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41117. }
  41118. }
  41119. };
  41120. /**
  41121. * Prepares the list of attributes required for instances according to the effect defines.
  41122. * @param attribs The current list of supported attribs
  41123. * @param defines The current Defines of the effect
  41124. */
  41125. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41126. if (defines["INSTANCES"]) {
  41127. attribs.push("world0");
  41128. attribs.push("world1");
  41129. attribs.push("world2");
  41130. attribs.push("world3");
  41131. }
  41132. };
  41133. /**
  41134. * Binds the light shadow information to the effect for the given mesh.
  41135. * @param light The light containing the generator
  41136. * @param scene The scene the lights belongs to
  41137. * @param mesh The mesh we are binding the information to render
  41138. * @param lightIndex The light index in the effect used to render the mesh
  41139. * @param effect The effect we are binding the data to
  41140. */
  41141. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41142. if (light.shadowEnabled && mesh.receiveShadows) {
  41143. var shadowGenerator = light.getShadowGenerator();
  41144. if (shadowGenerator) {
  41145. shadowGenerator.bindShadowLight(lightIndex, effect);
  41146. }
  41147. }
  41148. };
  41149. /**
  41150. * Binds the light information to the effect.
  41151. * @param light The light containing the generator
  41152. * @param effect The effect we are binding the data to
  41153. * @param lightIndex The light index in the effect used to render
  41154. */
  41155. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41156. light.transferToEffect(effect, lightIndex + "");
  41157. };
  41158. /**
  41159. * Binds the lights information from the scene to the effect for the given mesh.
  41160. * @param scene The scene the lights belongs to
  41161. * @param mesh The mesh we are binding the information to render
  41162. * @param effect The effect we are binding the data to
  41163. * @param defines The generated defines for the effect
  41164. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41165. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41166. */
  41167. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41168. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41169. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41170. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41171. for (var i = 0; i < len; i++) {
  41172. var light = mesh._lightSources[i];
  41173. var iAsString = i.toString();
  41174. var scaledIntensity = light.getScaledIntensity();
  41175. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41176. MaterialHelper.BindLightProperties(light, effect, i);
  41177. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41178. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41179. if (defines["SPECULARTERM"]) {
  41180. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41181. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41182. }
  41183. // Shadows
  41184. if (scene.shadowsEnabled) {
  41185. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41186. }
  41187. light._uniformBuffer.update();
  41188. }
  41189. };
  41190. /**
  41191. * Binds the fog information from the scene to the effect for the given mesh.
  41192. * @param scene The scene the lights belongs to
  41193. * @param mesh The mesh we are binding the information to render
  41194. * @param effect The effect we are binding the data to
  41195. */
  41196. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41197. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41198. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41199. effect.setColor3("vFogColor", scene.fogColor);
  41200. }
  41201. };
  41202. /**
  41203. * Binds the bones information from the mesh to the effect.
  41204. * @param mesh The mesh we are binding the information to render
  41205. * @param effect The effect we are binding the data to
  41206. */
  41207. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41208. if (!effect || !mesh) {
  41209. return;
  41210. }
  41211. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41212. mesh.computeBonesUsingShaders = false;
  41213. }
  41214. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41215. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41216. if (matrices) {
  41217. effect.setMatrices("mBones", matrices);
  41218. }
  41219. }
  41220. };
  41221. /**
  41222. * Binds the morph targets information from the mesh to the effect.
  41223. * @param abstractMesh The mesh we are binding the information to render
  41224. * @param effect The effect we are binding the data to
  41225. */
  41226. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41227. var manager = abstractMesh.morphTargetManager;
  41228. if (!abstractMesh || !manager) {
  41229. return;
  41230. }
  41231. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41232. };
  41233. /**
  41234. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41235. * @param defines The generated defines used in the effect
  41236. * @param effect The effect we are binding the data to
  41237. * @param scene The scene we are willing to render with logarithmic scale for
  41238. */
  41239. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41240. if (defines["LOGARITHMICDEPTH"]) {
  41241. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41242. }
  41243. };
  41244. /**
  41245. * Binds the clip plane information from the scene to the effect.
  41246. * @param scene The scene the clip plane information are extracted from
  41247. * @param effect The effect we are binding the data to
  41248. */
  41249. MaterialHelper.BindClipPlane = function (effect, scene) {
  41250. if (scene.clipPlane) {
  41251. var clipPlane = scene.clipPlane;
  41252. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41253. }
  41254. };
  41255. return MaterialHelper;
  41256. }());
  41257. BABYLON.MaterialHelper = MaterialHelper;
  41258. })(BABYLON || (BABYLON = {}));
  41259. //# sourceMappingURL=babylon.materialHelper.js.map
  41260. var BABYLON;
  41261. (function (BABYLON) {
  41262. var PushMaterial = /** @class */ (function (_super) {
  41263. __extends(PushMaterial, _super);
  41264. function PushMaterial(name, scene) {
  41265. var _this = _super.call(this, name, scene) || this;
  41266. _this._normalMatrix = new BABYLON.Matrix();
  41267. _this.storeEffectOnSubMeshes = true;
  41268. return _this;
  41269. }
  41270. PushMaterial.prototype.getEffect = function () {
  41271. return this._activeEffect;
  41272. };
  41273. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41274. if (!mesh) {
  41275. return false;
  41276. }
  41277. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41278. return true;
  41279. }
  41280. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41281. };
  41282. /**
  41283. * Binds the given world matrix to the active effect
  41284. *
  41285. * @param world the matrix to bind
  41286. */
  41287. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41288. this._activeEffect.setMatrix("world", world);
  41289. };
  41290. /**
  41291. * Binds the given normal matrix to the active effect
  41292. *
  41293. * @param normalMatrix the matrix to bind
  41294. */
  41295. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41296. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41297. };
  41298. PushMaterial.prototype.bind = function (world, mesh) {
  41299. if (!mesh) {
  41300. return;
  41301. }
  41302. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41303. };
  41304. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41305. if (effect === void 0) { effect = null; }
  41306. _super.prototype._afterBind.call(this, mesh);
  41307. this.getScene()._cachedEffect = effect;
  41308. };
  41309. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41310. if (visibility === void 0) { visibility = 1; }
  41311. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41312. };
  41313. return PushMaterial;
  41314. }(BABYLON.Material));
  41315. BABYLON.PushMaterial = PushMaterial;
  41316. })(BABYLON || (BABYLON = {}));
  41317. //# sourceMappingURL=babylon.pushMaterial.js.map
  41318. var BABYLON;
  41319. (function (BABYLON) {
  41320. /** @hidden */
  41321. var StandardMaterialDefines = /** @class */ (function (_super) {
  41322. __extends(StandardMaterialDefines, _super);
  41323. function StandardMaterialDefines() {
  41324. var _this = _super.call(this) || this;
  41325. _this.MAINUV1 = false;
  41326. _this.MAINUV2 = false;
  41327. _this.DIFFUSE = false;
  41328. _this.DIFFUSEDIRECTUV = 0;
  41329. _this.AMBIENT = false;
  41330. _this.AMBIENTDIRECTUV = 0;
  41331. _this.OPACITY = false;
  41332. _this.OPACITYDIRECTUV = 0;
  41333. _this.OPACITYRGB = false;
  41334. _this.REFLECTION = false;
  41335. _this.EMISSIVE = false;
  41336. _this.EMISSIVEDIRECTUV = 0;
  41337. _this.SPECULAR = false;
  41338. _this.SPECULARDIRECTUV = 0;
  41339. _this.BUMP = false;
  41340. _this.BUMPDIRECTUV = 0;
  41341. _this.PARALLAX = false;
  41342. _this.PARALLAXOCCLUSION = false;
  41343. _this.SPECULAROVERALPHA = false;
  41344. _this.CLIPPLANE = false;
  41345. _this.ALPHATEST = false;
  41346. _this.DEPTHPREPASS = false;
  41347. _this.ALPHAFROMDIFFUSE = false;
  41348. _this.POINTSIZE = false;
  41349. _this.FOG = false;
  41350. _this.SPECULARTERM = false;
  41351. _this.DIFFUSEFRESNEL = false;
  41352. _this.OPACITYFRESNEL = false;
  41353. _this.REFLECTIONFRESNEL = false;
  41354. _this.REFRACTIONFRESNEL = false;
  41355. _this.EMISSIVEFRESNEL = false;
  41356. _this.FRESNEL = false;
  41357. _this.NORMAL = false;
  41358. _this.UV1 = false;
  41359. _this.UV2 = false;
  41360. _this.VERTEXCOLOR = false;
  41361. _this.VERTEXALPHA = false;
  41362. _this.NUM_BONE_INFLUENCERS = 0;
  41363. _this.BonesPerMesh = 0;
  41364. _this.INSTANCES = false;
  41365. _this.GLOSSINESS = false;
  41366. _this.ROUGHNESS = false;
  41367. _this.EMISSIVEASILLUMINATION = false;
  41368. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41369. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41370. _this.LIGHTMAP = false;
  41371. _this.LIGHTMAPDIRECTUV = 0;
  41372. _this.OBJECTSPACE_NORMALMAP = false;
  41373. _this.USELIGHTMAPASSHADOWMAP = false;
  41374. _this.REFLECTIONMAP_3D = false;
  41375. _this.REFLECTIONMAP_SPHERICAL = false;
  41376. _this.REFLECTIONMAP_PLANAR = false;
  41377. _this.REFLECTIONMAP_CUBIC = false;
  41378. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41379. _this.REFLECTIONMAP_PROJECTION = false;
  41380. _this.REFLECTIONMAP_SKYBOX = false;
  41381. _this.REFLECTIONMAP_EXPLICIT = false;
  41382. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41383. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41384. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41385. _this.INVERTCUBICMAP = false;
  41386. _this.LOGARITHMICDEPTH = false;
  41387. _this.REFRACTION = false;
  41388. _this.REFRACTIONMAP_3D = false;
  41389. _this.REFLECTIONOVERALPHA = false;
  41390. _this.TWOSIDEDLIGHTING = false;
  41391. _this.SHADOWFLOAT = false;
  41392. _this.MORPHTARGETS = false;
  41393. _this.MORPHTARGETS_NORMAL = false;
  41394. _this.MORPHTARGETS_TANGENT = false;
  41395. _this.NUM_MORPH_INFLUENCERS = 0;
  41396. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41397. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41398. _this.IMAGEPROCESSING = false;
  41399. _this.VIGNETTE = false;
  41400. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41401. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41402. _this.TONEMAPPING = false;
  41403. _this.CONTRAST = false;
  41404. _this.COLORCURVES = false;
  41405. _this.COLORGRADING = false;
  41406. _this.COLORGRADING3D = false;
  41407. _this.SAMPLER3DGREENDEPTH = false;
  41408. _this.SAMPLER3DBGRMAP = false;
  41409. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41410. /**
  41411. * If the reflection texture on this material is in linear color space
  41412. * @hidden
  41413. */
  41414. _this.IS_REFLECTION_LINEAR = false;
  41415. /**
  41416. * If the refraction texture on this material is in linear color space
  41417. * @hidden
  41418. */
  41419. _this.IS_REFRACTION_LINEAR = false;
  41420. _this.EXPOSURE = false;
  41421. _this.rebuild();
  41422. return _this;
  41423. }
  41424. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41425. var modes = [
  41426. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41427. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41428. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41429. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41430. ];
  41431. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41432. var mode = modes_1[_i];
  41433. this[mode] = (mode === modeToEnable);
  41434. }
  41435. };
  41436. return StandardMaterialDefines;
  41437. }(BABYLON.MaterialDefines));
  41438. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41439. var StandardMaterial = /** @class */ (function (_super) {
  41440. __extends(StandardMaterial, _super);
  41441. function StandardMaterial(name, scene) {
  41442. var _this = _super.call(this, name, scene) || this;
  41443. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41444. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41445. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41446. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41447. _this.specularPower = 64;
  41448. _this._useAlphaFromDiffuseTexture = false;
  41449. _this._useEmissiveAsIllumination = false;
  41450. _this._linkEmissiveWithDiffuse = false;
  41451. _this._useSpecularOverAlpha = false;
  41452. _this._useReflectionOverAlpha = false;
  41453. _this._disableLighting = false;
  41454. _this._useObjectSpaceNormalMap = false;
  41455. _this._useParallax = false;
  41456. _this._useParallaxOcclusion = false;
  41457. _this.parallaxScaleBias = 0.05;
  41458. _this._roughness = 0;
  41459. _this.indexOfRefraction = 0.98;
  41460. _this.invertRefractionY = true;
  41461. /**
  41462. * Defines the alpha limits in alpha test mode
  41463. */
  41464. _this.alphaCutOff = 0.4;
  41465. _this._useLightmapAsShadowmap = false;
  41466. _this._useReflectionFresnelFromSpecular = false;
  41467. _this._useGlossinessFromSpecularMapAlpha = false;
  41468. _this._maxSimultaneousLights = 4;
  41469. /**
  41470. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41471. */
  41472. _this._invertNormalMapX = false;
  41473. /**
  41474. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41475. */
  41476. _this._invertNormalMapY = false;
  41477. /**
  41478. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41479. */
  41480. _this._twoSidedLighting = false;
  41481. _this._renderTargets = new BABYLON.SmartArray(16);
  41482. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41483. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41484. // Setup the default processing configuration to the scene.
  41485. _this._attachImageProcessingConfiguration(null);
  41486. _this.getRenderTargetTextures = function () {
  41487. _this._renderTargets.reset();
  41488. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41489. _this._renderTargets.push(_this._reflectionTexture);
  41490. }
  41491. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41492. _this._renderTargets.push(_this._refractionTexture);
  41493. }
  41494. return _this._renderTargets;
  41495. };
  41496. return _this;
  41497. }
  41498. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41499. /**
  41500. * Gets the image processing configuration used either in this material.
  41501. */
  41502. get: function () {
  41503. return this._imageProcessingConfiguration;
  41504. },
  41505. /**
  41506. * Sets the Default image processing configuration used either in the this material.
  41507. *
  41508. * If sets to null, the scene one is in use.
  41509. */
  41510. set: function (value) {
  41511. this._attachImageProcessingConfiguration(value);
  41512. // Ensure the effect will be rebuilt.
  41513. this._markAllSubMeshesAsTexturesDirty();
  41514. },
  41515. enumerable: true,
  41516. configurable: true
  41517. });
  41518. /**
  41519. * Attaches a new image processing configuration to the Standard Material.
  41520. * @param configuration
  41521. */
  41522. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41523. var _this = this;
  41524. if (configuration === this._imageProcessingConfiguration) {
  41525. return;
  41526. }
  41527. // Detaches observer.
  41528. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41529. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41530. }
  41531. // Pick the scene configuration if needed.
  41532. if (!configuration) {
  41533. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41534. }
  41535. else {
  41536. this._imageProcessingConfiguration = configuration;
  41537. }
  41538. // Attaches observer.
  41539. if (this._imageProcessingConfiguration) {
  41540. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41541. _this._markAllSubMeshesAsImageProcessingDirty();
  41542. });
  41543. }
  41544. };
  41545. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41546. /**
  41547. * Gets wether the color curves effect is enabled.
  41548. */
  41549. get: function () {
  41550. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41551. },
  41552. /**
  41553. * Sets wether the color curves effect is enabled.
  41554. */
  41555. set: function (value) {
  41556. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41557. },
  41558. enumerable: true,
  41559. configurable: true
  41560. });
  41561. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41562. /**
  41563. * Gets wether the color grading effect is enabled.
  41564. */
  41565. get: function () {
  41566. return this.imageProcessingConfiguration.colorGradingEnabled;
  41567. },
  41568. /**
  41569. * Gets wether the color grading effect is enabled.
  41570. */
  41571. set: function (value) {
  41572. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41573. },
  41574. enumerable: true,
  41575. configurable: true
  41576. });
  41577. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41578. /**
  41579. * Gets wether tonemapping is enabled or not.
  41580. */
  41581. get: function () {
  41582. return this._imageProcessingConfiguration.toneMappingEnabled;
  41583. },
  41584. /**
  41585. * Sets wether tonemapping is enabled or not
  41586. */
  41587. set: function (value) {
  41588. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41589. },
  41590. enumerable: true,
  41591. configurable: true
  41592. });
  41593. ;
  41594. ;
  41595. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41596. /**
  41597. * The camera exposure used on this material.
  41598. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41599. * This corresponds to a photographic exposure.
  41600. */
  41601. get: function () {
  41602. return this._imageProcessingConfiguration.exposure;
  41603. },
  41604. /**
  41605. * The camera exposure used on this material.
  41606. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41607. * This corresponds to a photographic exposure.
  41608. */
  41609. set: function (value) {
  41610. this._imageProcessingConfiguration.exposure = value;
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. ;
  41616. ;
  41617. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41618. /**
  41619. * Gets The camera contrast used on this material.
  41620. */
  41621. get: function () {
  41622. return this._imageProcessingConfiguration.contrast;
  41623. },
  41624. /**
  41625. * Sets The camera contrast used on this material.
  41626. */
  41627. set: function (value) {
  41628. this._imageProcessingConfiguration.contrast = value;
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41634. /**
  41635. * Gets the Color Grading 2D Lookup Texture.
  41636. */
  41637. get: function () {
  41638. return this._imageProcessingConfiguration.colorGradingTexture;
  41639. },
  41640. /**
  41641. * Sets the Color Grading 2D Lookup Texture.
  41642. */
  41643. set: function (value) {
  41644. this._imageProcessingConfiguration.colorGradingTexture = value;
  41645. },
  41646. enumerable: true,
  41647. configurable: true
  41648. });
  41649. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41650. /**
  41651. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41652. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41653. * 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;
  41654. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41655. */
  41656. get: function () {
  41657. return this._imageProcessingConfiguration.colorCurves;
  41658. },
  41659. /**
  41660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41662. * 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;
  41663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41664. */
  41665. set: function (value) {
  41666. this._imageProcessingConfiguration.colorCurves = value;
  41667. },
  41668. enumerable: true,
  41669. configurable: true
  41670. });
  41671. StandardMaterial.prototype.getClassName = function () {
  41672. return "StandardMaterial";
  41673. };
  41674. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41675. get: function () {
  41676. return this._useLogarithmicDepth;
  41677. },
  41678. set: function (value) {
  41679. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41680. this._markAllSubMeshesAsMiscDirty();
  41681. },
  41682. enumerable: true,
  41683. configurable: true
  41684. });
  41685. StandardMaterial.prototype.needAlphaBlending = function () {
  41686. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41687. };
  41688. StandardMaterial.prototype.needAlphaTesting = function () {
  41689. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41690. };
  41691. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41692. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41693. };
  41694. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41695. return this._diffuseTexture;
  41696. };
  41697. /**
  41698. * Child classes can use it to update shaders
  41699. */
  41700. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41701. if (useInstances === void 0) { useInstances = false; }
  41702. if (subMesh.effect && this.isFrozen) {
  41703. if (this._wasPreviouslyReady && subMesh.effect) {
  41704. return true;
  41705. }
  41706. }
  41707. if (!subMesh._materialDefines) {
  41708. subMesh._materialDefines = new StandardMaterialDefines();
  41709. }
  41710. var scene = this.getScene();
  41711. var defines = subMesh._materialDefines;
  41712. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41713. if (defines._renderId === scene.getRenderId()) {
  41714. return true;
  41715. }
  41716. }
  41717. var engine = scene.getEngine();
  41718. // Lights
  41719. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41720. // Textures
  41721. if (defines._areTexturesDirty) {
  41722. defines._needUVs = false;
  41723. defines.MAINUV1 = false;
  41724. defines.MAINUV2 = false;
  41725. if (scene.texturesEnabled) {
  41726. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41727. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41728. return false;
  41729. }
  41730. else {
  41731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41732. }
  41733. }
  41734. else {
  41735. defines.DIFFUSE = false;
  41736. }
  41737. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41738. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41739. return false;
  41740. }
  41741. else {
  41742. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41743. }
  41744. }
  41745. else {
  41746. defines.AMBIENT = false;
  41747. }
  41748. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41749. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41750. return false;
  41751. }
  41752. else {
  41753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41754. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41755. }
  41756. }
  41757. else {
  41758. defines.OPACITY = false;
  41759. }
  41760. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41761. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41762. return false;
  41763. }
  41764. else {
  41765. defines._needNormals = true;
  41766. defines.REFLECTION = true;
  41767. defines.ROUGHNESS = (this._roughness > 0);
  41768. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41769. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41770. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41771. switch (this._reflectionTexture.coordinatesMode) {
  41772. case BABYLON.Texture.EXPLICIT_MODE:
  41773. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41774. break;
  41775. case BABYLON.Texture.PLANAR_MODE:
  41776. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41777. break;
  41778. case BABYLON.Texture.PROJECTION_MODE:
  41779. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41780. break;
  41781. case BABYLON.Texture.SKYBOX_MODE:
  41782. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41783. break;
  41784. case BABYLON.Texture.SPHERICAL_MODE:
  41785. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41786. break;
  41787. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41788. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41789. break;
  41790. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41791. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41792. break;
  41793. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41794. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41795. break;
  41796. case BABYLON.Texture.CUBIC_MODE:
  41797. case BABYLON.Texture.INVCUBIC_MODE:
  41798. default:
  41799. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41800. break;
  41801. }
  41802. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41803. }
  41804. }
  41805. else {
  41806. defines.REFLECTION = false;
  41807. }
  41808. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41809. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41810. return false;
  41811. }
  41812. else {
  41813. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41814. }
  41815. }
  41816. else {
  41817. defines.EMISSIVE = false;
  41818. }
  41819. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41820. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41821. return false;
  41822. }
  41823. else {
  41824. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41825. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41826. }
  41827. }
  41828. else {
  41829. defines.LIGHTMAP = false;
  41830. }
  41831. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41832. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41833. return false;
  41834. }
  41835. else {
  41836. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41837. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41838. }
  41839. }
  41840. else {
  41841. defines.SPECULAR = false;
  41842. }
  41843. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41844. // Bump texure can not be not blocking.
  41845. if (!this._bumpTexture.isReady()) {
  41846. return false;
  41847. }
  41848. else {
  41849. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41850. defines.PARALLAX = this._useParallax;
  41851. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41852. }
  41853. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41854. }
  41855. else {
  41856. defines.BUMP = false;
  41857. }
  41858. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41859. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41860. return false;
  41861. }
  41862. else {
  41863. defines._needUVs = true;
  41864. defines.REFRACTION = true;
  41865. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41866. }
  41867. }
  41868. else {
  41869. defines.REFRACTION = false;
  41870. }
  41871. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41872. }
  41873. else {
  41874. defines.DIFFUSE = false;
  41875. defines.AMBIENT = false;
  41876. defines.OPACITY = false;
  41877. defines.REFLECTION = false;
  41878. defines.EMISSIVE = false;
  41879. defines.LIGHTMAP = false;
  41880. defines.BUMP = false;
  41881. defines.REFRACTION = false;
  41882. }
  41883. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41884. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41885. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41886. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41887. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41888. }
  41889. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41890. if (!this._imageProcessingConfiguration.isReady()) {
  41891. return false;
  41892. }
  41893. this._imageProcessingConfiguration.prepareDefines(defines);
  41894. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41895. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41896. }
  41897. if (defines._areFresnelDirty) {
  41898. if (StandardMaterial.FresnelEnabled) {
  41899. // Fresnel
  41900. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41901. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41902. this._reflectionFresnelParameters) {
  41903. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41904. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41905. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41906. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41907. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41908. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41909. defines._needNormals = true;
  41910. defines.FRESNEL = true;
  41911. }
  41912. }
  41913. else {
  41914. defines.FRESNEL = false;
  41915. }
  41916. }
  41917. // Misc.
  41918. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41919. // Attribs
  41920. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41921. // Values that need to be evaluated on every frame
  41922. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41923. // Get correct effect
  41924. if (defines.isDirty) {
  41925. defines.markAsProcessed();
  41926. scene.resetCachedMaterial();
  41927. // Fallbacks
  41928. var fallbacks = new BABYLON.EffectFallbacks();
  41929. if (defines.REFLECTION) {
  41930. fallbacks.addFallback(0, "REFLECTION");
  41931. }
  41932. if (defines.SPECULAR) {
  41933. fallbacks.addFallback(0, "SPECULAR");
  41934. }
  41935. if (defines.BUMP) {
  41936. fallbacks.addFallback(0, "BUMP");
  41937. }
  41938. if (defines.PARALLAX) {
  41939. fallbacks.addFallback(1, "PARALLAX");
  41940. }
  41941. if (defines.PARALLAXOCCLUSION) {
  41942. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41943. }
  41944. if (defines.SPECULAROVERALPHA) {
  41945. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41946. }
  41947. if (defines.FOG) {
  41948. fallbacks.addFallback(1, "FOG");
  41949. }
  41950. if (defines.POINTSIZE) {
  41951. fallbacks.addFallback(0, "POINTSIZE");
  41952. }
  41953. if (defines.LOGARITHMICDEPTH) {
  41954. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41955. }
  41956. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41957. if (defines.SPECULARTERM) {
  41958. fallbacks.addFallback(0, "SPECULARTERM");
  41959. }
  41960. if (defines.DIFFUSEFRESNEL) {
  41961. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41962. }
  41963. if (defines.OPACITYFRESNEL) {
  41964. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41965. }
  41966. if (defines.REFLECTIONFRESNEL) {
  41967. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41968. }
  41969. if (defines.EMISSIVEFRESNEL) {
  41970. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41971. }
  41972. if (defines.FRESNEL) {
  41973. fallbacks.addFallback(4, "FRESNEL");
  41974. }
  41975. //Attributes
  41976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41977. if (defines.NORMAL) {
  41978. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41979. }
  41980. if (defines.UV1) {
  41981. attribs.push(BABYLON.VertexBuffer.UVKind);
  41982. }
  41983. if (defines.UV2) {
  41984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41985. }
  41986. if (defines.VERTEXCOLOR) {
  41987. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41988. }
  41989. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41990. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41991. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41992. var shaderName = "default";
  41993. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41994. "vFogInfos", "vFogColor", "pointSize",
  41995. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41996. "mBones",
  41997. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41998. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41999. "vReflectionPosition", "vReflectionSize",
  42000. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42001. ];
  42002. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42003. var uniformBuffers = ["Material", "Scene"];
  42004. if (BABYLON.ImageProcessingConfiguration) {
  42005. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42006. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42007. }
  42008. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42009. uniformsNames: uniforms,
  42010. uniformBuffersNames: uniformBuffers,
  42011. samplers: samplers,
  42012. defines: defines,
  42013. maxSimultaneousLights: this._maxSimultaneousLights
  42014. });
  42015. if (this.customShaderNameResolve) {
  42016. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42017. }
  42018. var join = defines.toString();
  42019. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42020. attributes: attribs,
  42021. uniformsNames: uniforms,
  42022. uniformBuffersNames: uniformBuffers,
  42023. samplers: samplers,
  42024. defines: join,
  42025. fallbacks: fallbacks,
  42026. onCompiled: this.onCompiled,
  42027. onError: this.onError,
  42028. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42029. }, engine), defines);
  42030. this.buildUniformLayout();
  42031. }
  42032. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42033. return false;
  42034. }
  42035. defines._renderId = scene.getRenderId();
  42036. this._wasPreviouslyReady = true;
  42037. return true;
  42038. };
  42039. StandardMaterial.prototype.buildUniformLayout = function () {
  42040. // Order is important !
  42041. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42042. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42043. this._uniformBuffer.addUniform("opacityParts", 4);
  42044. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42045. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42046. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42047. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42048. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42049. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42050. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42051. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42052. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42053. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42054. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42055. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42056. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42057. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42058. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42059. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42060. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42061. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42062. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42063. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42064. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42065. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42066. this._uniformBuffer.addUniform("specularMatrix", 16);
  42067. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42068. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42069. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42070. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42071. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42072. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42073. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42074. this._uniformBuffer.addUniform("pointSize", 1);
  42075. this._uniformBuffer.create();
  42076. };
  42077. StandardMaterial.prototype.unbind = function () {
  42078. if (this._activeEffect) {
  42079. var needFlag = false;
  42080. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42081. this._activeEffect.setTexture("reflection2DSampler", null);
  42082. needFlag = true;
  42083. }
  42084. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42085. this._activeEffect.setTexture("refraction2DSampler", null);
  42086. needFlag = true;
  42087. }
  42088. if (needFlag) {
  42089. this._markAllSubMeshesAsTexturesDirty();
  42090. }
  42091. }
  42092. _super.prototype.unbind.call(this);
  42093. };
  42094. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42095. var scene = this.getScene();
  42096. var defines = subMesh._materialDefines;
  42097. if (!defines) {
  42098. return;
  42099. }
  42100. var effect = subMesh.effect;
  42101. if (!effect) {
  42102. return;
  42103. }
  42104. this._activeEffect = effect;
  42105. // Matrices
  42106. this.bindOnlyWorldMatrix(world);
  42107. // Normal Matrix
  42108. if (defines.OBJECTSPACE_NORMALMAP) {
  42109. world.toNormalMatrix(this._normalMatrix);
  42110. this.bindOnlyNormalMatrix(this._normalMatrix);
  42111. }
  42112. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42113. // Bones
  42114. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42115. if (mustRebind) {
  42116. this._uniformBuffer.bindToEffect(effect, "Material");
  42117. this.bindViewProjection(effect);
  42118. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42119. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42120. // Fresnel
  42121. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42122. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42123. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42124. }
  42125. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42126. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42127. }
  42128. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42129. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42130. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42131. }
  42132. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42133. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42134. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42135. }
  42136. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42137. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42138. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42139. }
  42140. }
  42141. // Textures
  42142. if (scene.texturesEnabled) {
  42143. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42144. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42145. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42146. if (this._diffuseTexture.hasAlpha) {
  42147. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42148. }
  42149. }
  42150. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42151. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42152. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42153. }
  42154. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42155. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42156. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42157. }
  42158. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42159. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42160. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42161. if (this._reflectionTexture.boundingBoxSize) {
  42162. var cubeTexture = this._reflectionTexture;
  42163. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42164. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42165. }
  42166. }
  42167. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42168. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42169. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42170. }
  42171. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42172. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42173. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42174. }
  42175. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42176. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42177. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42178. }
  42179. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42180. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42181. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42182. if (scene._mirroredCameraPosition) {
  42183. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42184. }
  42185. else {
  42186. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42187. }
  42188. }
  42189. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42190. var depth = 1.0;
  42191. if (!this._refractionTexture.isCube) {
  42192. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42193. if (this._refractionTexture.depth) {
  42194. depth = this._refractionTexture.depth;
  42195. }
  42196. }
  42197. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42198. }
  42199. }
  42200. // Point size
  42201. if (this.pointsCloud) {
  42202. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42203. }
  42204. if (defines.SPECULARTERM) {
  42205. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42206. }
  42207. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42208. // Diffuse
  42209. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42210. }
  42211. // Textures
  42212. if (scene.texturesEnabled) {
  42213. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42214. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42215. }
  42216. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42217. effect.setTexture("ambientSampler", this._ambientTexture);
  42218. }
  42219. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42220. effect.setTexture("opacitySampler", this._opacityTexture);
  42221. }
  42222. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42223. if (this._reflectionTexture.isCube) {
  42224. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42225. }
  42226. else {
  42227. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42228. }
  42229. }
  42230. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42231. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42232. }
  42233. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42234. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42235. }
  42236. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42237. effect.setTexture("specularSampler", this._specularTexture);
  42238. }
  42239. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42240. effect.setTexture("bumpSampler", this._bumpTexture);
  42241. }
  42242. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42243. var depth = 1.0;
  42244. if (this._refractionTexture.isCube) {
  42245. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42246. }
  42247. else {
  42248. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42249. }
  42250. }
  42251. }
  42252. // Clip plane
  42253. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42254. // Colors
  42255. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42256. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42257. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42258. }
  42259. if (mustRebind || !this.isFrozen) {
  42260. // Lights
  42261. if (scene.lightsEnabled && !this._disableLighting) {
  42262. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42263. }
  42264. // View
  42265. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42266. this.bindView(effect);
  42267. }
  42268. // Fog
  42269. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42270. // Morph targets
  42271. if (defines.NUM_MORPH_INFLUENCERS) {
  42272. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42273. }
  42274. // Log. depth
  42275. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42276. // image processing
  42277. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42278. this._imageProcessingConfiguration.bind(this._activeEffect);
  42279. }
  42280. }
  42281. this._uniformBuffer.update();
  42282. this._afterBind(mesh, this._activeEffect);
  42283. };
  42284. StandardMaterial.prototype.getAnimatables = function () {
  42285. var results = [];
  42286. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42287. results.push(this._diffuseTexture);
  42288. }
  42289. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42290. results.push(this._ambientTexture);
  42291. }
  42292. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42293. results.push(this._opacityTexture);
  42294. }
  42295. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42296. results.push(this._reflectionTexture);
  42297. }
  42298. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42299. results.push(this._emissiveTexture);
  42300. }
  42301. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42302. results.push(this._specularTexture);
  42303. }
  42304. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42305. results.push(this._bumpTexture);
  42306. }
  42307. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42308. results.push(this._lightmapTexture);
  42309. }
  42310. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42311. results.push(this._refractionTexture);
  42312. }
  42313. return results;
  42314. };
  42315. StandardMaterial.prototype.getActiveTextures = function () {
  42316. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42317. if (this._diffuseTexture) {
  42318. activeTextures.push(this._diffuseTexture);
  42319. }
  42320. if (this._ambientTexture) {
  42321. activeTextures.push(this._ambientTexture);
  42322. }
  42323. if (this._opacityTexture) {
  42324. activeTextures.push(this._opacityTexture);
  42325. }
  42326. if (this._reflectionTexture) {
  42327. activeTextures.push(this._reflectionTexture);
  42328. }
  42329. if (this._emissiveTexture) {
  42330. activeTextures.push(this._emissiveTexture);
  42331. }
  42332. if (this._specularTexture) {
  42333. activeTextures.push(this._specularTexture);
  42334. }
  42335. if (this._bumpTexture) {
  42336. activeTextures.push(this._bumpTexture);
  42337. }
  42338. if (this._lightmapTexture) {
  42339. activeTextures.push(this._lightmapTexture);
  42340. }
  42341. if (this._refractionTexture) {
  42342. activeTextures.push(this._refractionTexture);
  42343. }
  42344. return activeTextures;
  42345. };
  42346. StandardMaterial.prototype.hasTexture = function (texture) {
  42347. if (_super.prototype.hasTexture.call(this, texture)) {
  42348. return true;
  42349. }
  42350. if (this._diffuseTexture === texture) {
  42351. return true;
  42352. }
  42353. if (this._ambientTexture === texture) {
  42354. return true;
  42355. }
  42356. if (this._opacityTexture === texture) {
  42357. return true;
  42358. }
  42359. if (this._reflectionTexture === texture) {
  42360. return true;
  42361. }
  42362. if (this._emissiveTexture === texture) {
  42363. return true;
  42364. }
  42365. if (this._specularTexture === texture) {
  42366. return true;
  42367. }
  42368. if (this._bumpTexture === texture) {
  42369. return true;
  42370. }
  42371. if (this._lightmapTexture === texture) {
  42372. return true;
  42373. }
  42374. if (this._refractionTexture === texture) {
  42375. return true;
  42376. }
  42377. return false;
  42378. };
  42379. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42380. if (forceDisposeTextures) {
  42381. if (this._diffuseTexture) {
  42382. this._diffuseTexture.dispose();
  42383. }
  42384. if (this._ambientTexture) {
  42385. this._ambientTexture.dispose();
  42386. }
  42387. if (this._opacityTexture) {
  42388. this._opacityTexture.dispose();
  42389. }
  42390. if (this._reflectionTexture) {
  42391. this._reflectionTexture.dispose();
  42392. }
  42393. if (this._emissiveTexture) {
  42394. this._emissiveTexture.dispose();
  42395. }
  42396. if (this._specularTexture) {
  42397. this._specularTexture.dispose();
  42398. }
  42399. if (this._bumpTexture) {
  42400. this._bumpTexture.dispose();
  42401. }
  42402. if (this._lightmapTexture) {
  42403. this._lightmapTexture.dispose();
  42404. }
  42405. if (this._refractionTexture) {
  42406. this._refractionTexture.dispose();
  42407. }
  42408. }
  42409. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42410. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42411. }
  42412. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42413. };
  42414. StandardMaterial.prototype.clone = function (name) {
  42415. var _this = this;
  42416. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42417. result.name = name;
  42418. result.id = name;
  42419. return result;
  42420. };
  42421. StandardMaterial.prototype.serialize = function () {
  42422. return BABYLON.SerializationHelper.Serialize(this);
  42423. };
  42424. // Statics
  42425. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42426. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42427. };
  42428. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42429. get: function () {
  42430. return StandardMaterial._DiffuseTextureEnabled;
  42431. },
  42432. set: function (value) {
  42433. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42434. return;
  42435. }
  42436. StandardMaterial._DiffuseTextureEnabled = value;
  42437. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42438. },
  42439. enumerable: true,
  42440. configurable: true
  42441. });
  42442. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42443. get: function () {
  42444. return StandardMaterial._AmbientTextureEnabled;
  42445. },
  42446. set: function (value) {
  42447. if (StandardMaterial._AmbientTextureEnabled === value) {
  42448. return;
  42449. }
  42450. StandardMaterial._AmbientTextureEnabled = value;
  42451. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42452. },
  42453. enumerable: true,
  42454. configurable: true
  42455. });
  42456. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42457. get: function () {
  42458. return StandardMaterial._OpacityTextureEnabled;
  42459. },
  42460. set: function (value) {
  42461. if (StandardMaterial._OpacityTextureEnabled === value) {
  42462. return;
  42463. }
  42464. StandardMaterial._OpacityTextureEnabled = value;
  42465. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42466. },
  42467. enumerable: true,
  42468. configurable: true
  42469. });
  42470. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42471. get: function () {
  42472. return StandardMaterial._ReflectionTextureEnabled;
  42473. },
  42474. set: function (value) {
  42475. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42476. return;
  42477. }
  42478. StandardMaterial._ReflectionTextureEnabled = value;
  42479. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42485. get: function () {
  42486. return StandardMaterial._EmissiveTextureEnabled;
  42487. },
  42488. set: function (value) {
  42489. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42490. return;
  42491. }
  42492. StandardMaterial._EmissiveTextureEnabled = value;
  42493. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42494. },
  42495. enumerable: true,
  42496. configurable: true
  42497. });
  42498. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42499. get: function () {
  42500. return StandardMaterial._SpecularTextureEnabled;
  42501. },
  42502. set: function (value) {
  42503. if (StandardMaterial._SpecularTextureEnabled === value) {
  42504. return;
  42505. }
  42506. StandardMaterial._SpecularTextureEnabled = value;
  42507. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42508. },
  42509. enumerable: true,
  42510. configurable: true
  42511. });
  42512. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42513. get: function () {
  42514. return StandardMaterial._BumpTextureEnabled;
  42515. },
  42516. set: function (value) {
  42517. if (StandardMaterial._BumpTextureEnabled === value) {
  42518. return;
  42519. }
  42520. StandardMaterial._BumpTextureEnabled = value;
  42521. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42522. },
  42523. enumerable: true,
  42524. configurable: true
  42525. });
  42526. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42527. get: function () {
  42528. return StandardMaterial._LightmapTextureEnabled;
  42529. },
  42530. set: function (value) {
  42531. if (StandardMaterial._LightmapTextureEnabled === value) {
  42532. return;
  42533. }
  42534. StandardMaterial._LightmapTextureEnabled = value;
  42535. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42536. },
  42537. enumerable: true,
  42538. configurable: true
  42539. });
  42540. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42541. get: function () {
  42542. return StandardMaterial._RefractionTextureEnabled;
  42543. },
  42544. set: function (value) {
  42545. if (StandardMaterial._RefractionTextureEnabled === value) {
  42546. return;
  42547. }
  42548. StandardMaterial._RefractionTextureEnabled = value;
  42549. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42550. },
  42551. enumerable: true,
  42552. configurable: true
  42553. });
  42554. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42555. get: function () {
  42556. return StandardMaterial._ColorGradingTextureEnabled;
  42557. },
  42558. set: function (value) {
  42559. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42560. return;
  42561. }
  42562. StandardMaterial._ColorGradingTextureEnabled = value;
  42563. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42564. },
  42565. enumerable: true,
  42566. configurable: true
  42567. });
  42568. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42569. get: function () {
  42570. return StandardMaterial._FresnelEnabled;
  42571. },
  42572. set: function (value) {
  42573. if (StandardMaterial._FresnelEnabled === value) {
  42574. return;
  42575. }
  42576. StandardMaterial._FresnelEnabled = value;
  42577. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42578. },
  42579. enumerable: true,
  42580. configurable: true
  42581. });
  42582. // Flags used to enable or disable a type of texture for all Standard Materials
  42583. StandardMaterial._DiffuseTextureEnabled = true;
  42584. StandardMaterial._AmbientTextureEnabled = true;
  42585. StandardMaterial._OpacityTextureEnabled = true;
  42586. StandardMaterial._ReflectionTextureEnabled = true;
  42587. StandardMaterial._EmissiveTextureEnabled = true;
  42588. StandardMaterial._SpecularTextureEnabled = true;
  42589. StandardMaterial._BumpTextureEnabled = true;
  42590. StandardMaterial._LightmapTextureEnabled = true;
  42591. StandardMaterial._RefractionTextureEnabled = true;
  42592. StandardMaterial._ColorGradingTextureEnabled = true;
  42593. StandardMaterial._FresnelEnabled = true;
  42594. __decorate([
  42595. BABYLON.serializeAsTexture("diffuseTexture")
  42596. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42597. __decorate([
  42598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42599. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42600. __decorate([
  42601. BABYLON.serializeAsTexture("ambientTexture")
  42602. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42603. __decorate([
  42604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42605. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42606. __decorate([
  42607. BABYLON.serializeAsTexture("opacityTexture")
  42608. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42609. __decorate([
  42610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42611. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42612. __decorate([
  42613. BABYLON.serializeAsTexture("reflectionTexture")
  42614. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42615. __decorate([
  42616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42617. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42618. __decorate([
  42619. BABYLON.serializeAsTexture("emissiveTexture")
  42620. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42621. __decorate([
  42622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42623. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42624. __decorate([
  42625. BABYLON.serializeAsTexture("specularTexture")
  42626. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42627. __decorate([
  42628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42629. ], StandardMaterial.prototype, "specularTexture", void 0);
  42630. __decorate([
  42631. BABYLON.serializeAsTexture("bumpTexture")
  42632. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42633. __decorate([
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42635. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42636. __decorate([
  42637. BABYLON.serializeAsTexture("lightmapTexture")
  42638. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42639. __decorate([
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42641. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42642. __decorate([
  42643. BABYLON.serializeAsTexture("refractionTexture")
  42644. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42645. __decorate([
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42647. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42648. __decorate([
  42649. BABYLON.serializeAsColor3("ambient")
  42650. ], StandardMaterial.prototype, "ambientColor", void 0);
  42651. __decorate([
  42652. BABYLON.serializeAsColor3("diffuse")
  42653. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42654. __decorate([
  42655. BABYLON.serializeAsColor3("specular")
  42656. ], StandardMaterial.prototype, "specularColor", void 0);
  42657. __decorate([
  42658. BABYLON.serializeAsColor3("emissive")
  42659. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42660. __decorate([
  42661. BABYLON.serialize()
  42662. ], StandardMaterial.prototype, "specularPower", void 0);
  42663. __decorate([
  42664. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42665. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42666. __decorate([
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42668. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42669. __decorate([
  42670. BABYLON.serialize("useEmissiveAsIllumination")
  42671. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42672. __decorate([
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42675. __decorate([
  42676. BABYLON.serialize("linkEmissiveWithDiffuse")
  42677. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42678. __decorate([
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42681. __decorate([
  42682. BABYLON.serialize("useSpecularOverAlpha")
  42683. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42684. __decorate([
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42687. __decorate([
  42688. BABYLON.serialize("useReflectionOverAlpha")
  42689. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42690. __decorate([
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42692. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42693. __decorate([
  42694. BABYLON.serialize("disableLighting")
  42695. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42696. __decorate([
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42698. ], StandardMaterial.prototype, "disableLighting", void 0);
  42699. __decorate([
  42700. BABYLON.serialize("useObjectSpaceNormalMap")
  42701. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42702. __decorate([
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42704. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42705. __decorate([
  42706. BABYLON.serialize("useParallax")
  42707. ], StandardMaterial.prototype, "_useParallax", void 0);
  42708. __decorate([
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], StandardMaterial.prototype, "useParallax", void 0);
  42711. __decorate([
  42712. BABYLON.serialize("useParallaxOcclusion")
  42713. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42714. __decorate([
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42716. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42717. __decorate([
  42718. BABYLON.serialize()
  42719. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42720. __decorate([
  42721. BABYLON.serialize("roughness")
  42722. ], StandardMaterial.prototype, "_roughness", void 0);
  42723. __decorate([
  42724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42725. ], StandardMaterial.prototype, "roughness", void 0);
  42726. __decorate([
  42727. BABYLON.serialize()
  42728. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42729. __decorate([
  42730. BABYLON.serialize()
  42731. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42732. __decorate([
  42733. BABYLON.serialize()
  42734. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42735. __decorate([
  42736. BABYLON.serialize("useLightmapAsShadowmap")
  42737. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42738. __decorate([
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42740. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42741. __decorate([
  42742. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42743. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42744. __decorate([
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42746. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42747. __decorate([
  42748. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42749. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42750. __decorate([
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42752. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42753. __decorate([
  42754. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42755. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42756. __decorate([
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42758. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42759. __decorate([
  42760. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42761. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42762. __decorate([
  42763. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42764. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42765. __decorate([
  42766. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42767. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42768. __decorate([
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42770. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42771. __decorate([
  42772. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42773. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42774. __decorate([
  42775. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42776. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42777. __decorate([
  42778. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42779. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42780. __decorate([
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42783. __decorate([
  42784. BABYLON.serialize("maxSimultaneousLights")
  42785. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42786. __decorate([
  42787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42788. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42789. __decorate([
  42790. BABYLON.serialize("invertNormalMapX")
  42791. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42792. __decorate([
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42794. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42795. __decorate([
  42796. BABYLON.serialize("invertNormalMapY")
  42797. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42798. __decorate([
  42799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42800. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42801. __decorate([
  42802. BABYLON.serialize("twoSidedLighting")
  42803. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42804. __decorate([
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42806. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42807. __decorate([
  42808. BABYLON.serialize()
  42809. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42810. return StandardMaterial;
  42811. }(BABYLON.PushMaterial));
  42812. BABYLON.StandardMaterial = StandardMaterial;
  42813. })(BABYLON || (BABYLON = {}));
  42814. //# sourceMappingURL=babylon.standardMaterial.js.map
  42815. var BABYLON;
  42816. (function (BABYLON) {
  42817. /**
  42818. * Manages the defines for the PBR Material.
  42819. * @hiddenChildren
  42820. */
  42821. var PBRMaterialDefines = /** @class */ (function (_super) {
  42822. __extends(PBRMaterialDefines, _super);
  42823. /**
  42824. * Initializes the PBR Material defines.
  42825. */
  42826. function PBRMaterialDefines() {
  42827. var _this = _super.call(this) || this;
  42828. _this.PBR = true;
  42829. _this.MAINUV1 = false;
  42830. _this.MAINUV2 = false;
  42831. _this.UV1 = false;
  42832. _this.UV2 = false;
  42833. _this.ALBEDO = false;
  42834. _this.ALBEDODIRECTUV = 0;
  42835. _this.VERTEXCOLOR = false;
  42836. _this.AMBIENT = false;
  42837. _this.AMBIENTDIRECTUV = 0;
  42838. _this.AMBIENTINGRAYSCALE = false;
  42839. _this.OPACITY = false;
  42840. _this.VERTEXALPHA = false;
  42841. _this.OPACITYDIRECTUV = 0;
  42842. _this.OPACITYRGB = false;
  42843. _this.ALPHATEST = false;
  42844. _this.DEPTHPREPASS = false;
  42845. _this.ALPHABLEND = false;
  42846. _this.ALPHAFROMALBEDO = false;
  42847. _this.ALPHATESTVALUE = "0.5";
  42848. _this.SPECULAROVERALPHA = false;
  42849. _this.RADIANCEOVERALPHA = false;
  42850. _this.ALPHAFRESNEL = false;
  42851. _this.LINEARALPHAFRESNEL = false;
  42852. _this.PREMULTIPLYALPHA = false;
  42853. _this.EMISSIVE = false;
  42854. _this.EMISSIVEDIRECTUV = 0;
  42855. _this.REFLECTIVITY = false;
  42856. _this.REFLECTIVITYDIRECTUV = 0;
  42857. _this.SPECULARTERM = false;
  42858. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  42859. _this.MICROSURFACEAUTOMATIC = false;
  42860. _this.LODBASEDMICROSFURACE = false;
  42861. _this.MICROSURFACEMAP = false;
  42862. _this.MICROSURFACEMAPDIRECTUV = 0;
  42863. _this.METALLICWORKFLOW = false;
  42864. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  42865. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  42866. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  42867. _this.AOSTOREINMETALMAPRED = false;
  42868. _this.ENVIRONMENTBRDF = false;
  42869. _this.NORMAL = false;
  42870. _this.TANGENT = false;
  42871. _this.BUMP = false;
  42872. _this.BUMPDIRECTUV = 0;
  42873. _this.OBJECTSPACE_NORMALMAP = false;
  42874. _this.PARALLAX = false;
  42875. _this.PARALLAXOCCLUSION = false;
  42876. _this.NORMALXYSCALE = true;
  42877. _this.LIGHTMAP = false;
  42878. _this.LIGHTMAPDIRECTUV = 0;
  42879. _this.USELIGHTMAPASSHADOWMAP = false;
  42880. _this.GAMMALIGHTMAP = false;
  42881. _this.REFLECTION = false;
  42882. _this.REFLECTIONMAP_3D = false;
  42883. _this.REFLECTIONMAP_SPHERICAL = false;
  42884. _this.REFLECTIONMAP_PLANAR = false;
  42885. _this.REFLECTIONMAP_CUBIC = false;
  42886. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42887. _this.REFLECTIONMAP_PROJECTION = false;
  42888. _this.REFLECTIONMAP_SKYBOX = false;
  42889. _this.REFLECTIONMAP_EXPLICIT = false;
  42890. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42891. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42892. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42893. _this.INVERTCUBICMAP = false;
  42894. _this.USESPHERICALFROMREFLECTIONMAP = false;
  42895. _this.USESPHERICALINVERTEX = false;
  42896. _this.REFLECTIONMAP_OPPOSITEZ = false;
  42897. _this.LODINREFLECTIONALPHA = false;
  42898. _this.GAMMAREFLECTION = false;
  42899. _this.RGBDREFLECTION = false;
  42900. _this.RADIANCEOCCLUSION = false;
  42901. _this.HORIZONOCCLUSION = false;
  42902. _this.REFRACTION = false;
  42903. _this.REFRACTIONMAP_3D = false;
  42904. _this.REFRACTIONMAP_OPPOSITEZ = false;
  42905. _this.LODINREFRACTIONALPHA = false;
  42906. _this.GAMMAREFRACTION = false;
  42907. _this.RGBDREFRACTION = false;
  42908. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  42909. _this.INSTANCES = false;
  42910. _this.NUM_BONE_INFLUENCERS = 0;
  42911. _this.BonesPerMesh = 0;
  42912. _this.NONUNIFORMSCALING = false;
  42913. _this.MORPHTARGETS = false;
  42914. _this.MORPHTARGETS_NORMAL = false;
  42915. _this.MORPHTARGETS_TANGENT = false;
  42916. _this.NUM_MORPH_INFLUENCERS = 0;
  42917. _this.IMAGEPROCESSING = false;
  42918. _this.VIGNETTE = false;
  42919. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42920. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42921. _this.TONEMAPPING = false;
  42922. _this.CONTRAST = false;
  42923. _this.COLORCURVES = false;
  42924. _this.COLORGRADING = false;
  42925. _this.COLORGRADING3D = false;
  42926. _this.SAMPLER3DGREENDEPTH = false;
  42927. _this.SAMPLER3DBGRMAP = false;
  42928. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42929. _this.EXPOSURE = false;
  42930. _this.USEPHYSICALLIGHTFALLOFF = false;
  42931. _this.TWOSIDEDLIGHTING = false;
  42932. _this.SHADOWFLOAT = false;
  42933. _this.CLIPPLANE = false;
  42934. _this.POINTSIZE = false;
  42935. _this.FOG = false;
  42936. _this.LOGARITHMICDEPTH = false;
  42937. _this.FORCENORMALFORWARD = false;
  42938. _this.SPECULARAA = false;
  42939. _this.UNLIT = false;
  42940. _this.rebuild();
  42941. return _this;
  42942. }
  42943. /**
  42944. * Resets the PBR Material defines.
  42945. */
  42946. PBRMaterialDefines.prototype.reset = function () {
  42947. _super.prototype.reset.call(this);
  42948. this.ALPHATESTVALUE = "0.5";
  42949. this.PBR = true;
  42950. };
  42951. return PBRMaterialDefines;
  42952. }(BABYLON.MaterialDefines));
  42953. /**
  42954. * The Physically based material base class of BJS.
  42955. *
  42956. * This offers the main features of a standard PBR material.
  42957. * For more information, please refer to the documentation :
  42958. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42959. */
  42960. var PBRBaseMaterial = /** @class */ (function (_super) {
  42961. __extends(PBRBaseMaterial, _super);
  42962. /**
  42963. * Instantiates a new PBRMaterial instance.
  42964. *
  42965. * @param name The material name
  42966. * @param scene The scene the material will be use in.
  42967. */
  42968. function PBRBaseMaterial(name, scene) {
  42969. var _this = _super.call(this, name, scene) || this;
  42970. /**
  42971. * Intensity of the direct lights e.g. the four lights available in your scene.
  42972. * This impacts both the direct diffuse and specular highlights.
  42973. */
  42974. _this._directIntensity = 1.0;
  42975. /**
  42976. * Intensity of the emissive part of the material.
  42977. * This helps controlling the emissive effect without modifying the emissive color.
  42978. */
  42979. _this._emissiveIntensity = 1.0;
  42980. /**
  42981. * Intensity of the environment e.g. how much the environment will light the object
  42982. * either through harmonics for rough material or through the refelction for shiny ones.
  42983. */
  42984. _this._environmentIntensity = 1.0;
  42985. /**
  42986. * This is a special control allowing the reduction of the specular highlights coming from the
  42987. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42988. */
  42989. _this._specularIntensity = 1.0;
  42990. /**
  42991. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  42992. */
  42993. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  42994. /**
  42995. * Debug Control allowing disabling the bump map on this material.
  42996. */
  42997. _this._disableBumpMap = false;
  42998. /**
  42999. * AKA Occlusion Texture Intensity in other nomenclature.
  43000. */
  43001. _this._ambientTextureStrength = 1.0;
  43002. /**
  43003. * The color of a material in ambient lighting.
  43004. */
  43005. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43006. /**
  43007. * AKA Diffuse Color in other nomenclature.
  43008. */
  43009. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43010. /**
  43011. * AKA Specular Color in other nomenclature.
  43012. */
  43013. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43014. /**
  43015. * The color applied when light is reflected from a material.
  43016. */
  43017. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43018. /**
  43019. * The color applied when light is emitted from a material.
  43020. */
  43021. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43022. /**
  43023. * AKA Glossiness in other nomenclature.
  43024. */
  43025. _this._microSurface = 0.9;
  43026. /**
  43027. * source material index of refraction (IOR)' / 'destination material IOR.
  43028. */
  43029. _this._indexOfRefraction = 0.66;
  43030. /**
  43031. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43032. */
  43033. _this._invertRefractionY = false;
  43034. /**
  43035. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43036. * Materials half opaque for instance using refraction could benefit from this control.
  43037. */
  43038. _this._linkRefractionWithTransparency = false;
  43039. /**
  43040. * Specifies that the material will use the light map as a show map.
  43041. */
  43042. _this._useLightmapAsShadowmap = false;
  43043. /**
  43044. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43045. * makes the reflect vector face the model (under horizon).
  43046. */
  43047. _this._useHorizonOcclusion = true;
  43048. /**
  43049. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43050. * too much the area relying on ambient texture to define their ambient occlusion.
  43051. */
  43052. _this._useRadianceOcclusion = true;
  43053. /**
  43054. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43055. */
  43056. _this._useAlphaFromAlbedoTexture = false;
  43057. /**
  43058. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43059. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43060. */
  43061. _this._useSpecularOverAlpha = true;
  43062. /**
  43063. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43064. */
  43065. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43066. /**
  43067. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43068. */
  43069. _this._useRoughnessFromMetallicTextureAlpha = true;
  43070. /**
  43071. * Specifies if the metallic texture contains the roughness information in its green channel.
  43072. */
  43073. _this._useRoughnessFromMetallicTextureGreen = false;
  43074. /**
  43075. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43076. */
  43077. _this._useMetallnessFromMetallicTextureBlue = false;
  43078. /**
  43079. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43080. */
  43081. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43082. /**
  43083. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43084. */
  43085. _this._useAmbientInGrayScale = false;
  43086. /**
  43087. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43088. * The material will try to infer what glossiness each pixel should be.
  43089. */
  43090. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43091. /**
  43092. * BJS is using an harcoded light falloff based on a manually sets up range.
  43093. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43094. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43095. */
  43096. _this._usePhysicalLightFalloff = true;
  43097. /**
  43098. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43099. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43100. */
  43101. _this._useRadianceOverAlpha = true;
  43102. /**
  43103. * Allows using an object space normal map (instead of tangent space).
  43104. */
  43105. _this._useObjectSpaceNormalMap = false;
  43106. /**
  43107. * Allows using the bump map in parallax mode.
  43108. */
  43109. _this._useParallax = false;
  43110. /**
  43111. * Allows using the bump map in parallax occlusion mode.
  43112. */
  43113. _this._useParallaxOcclusion = false;
  43114. /**
  43115. * Controls the scale bias of the parallax mode.
  43116. */
  43117. _this._parallaxScaleBias = 0.05;
  43118. /**
  43119. * If sets to true, disables all the lights affecting the material.
  43120. */
  43121. _this._disableLighting = false;
  43122. /**
  43123. * Number of Simultaneous lights allowed on the material.
  43124. */
  43125. _this._maxSimultaneousLights = 4;
  43126. /**
  43127. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43128. */
  43129. _this._invertNormalMapX = false;
  43130. /**
  43131. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43132. */
  43133. _this._invertNormalMapY = false;
  43134. /**
  43135. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43136. */
  43137. _this._twoSidedLighting = false;
  43138. /**
  43139. * Defines the alpha limits in alpha test mode.
  43140. */
  43141. _this._alphaCutOff = 0.4;
  43142. /**
  43143. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43144. */
  43145. _this._forceAlphaTest = false;
  43146. /**
  43147. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43148. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43149. */
  43150. _this._useAlphaFresnel = false;
  43151. /**
  43152. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43153. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43154. */
  43155. _this._useLinearAlphaFresnel = false;
  43156. /**
  43157. * The transparency mode of the material.
  43158. */
  43159. _this._transparencyMode = null;
  43160. /**
  43161. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43162. * from cos thetav and roughness:
  43163. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43164. */
  43165. _this._environmentBRDFTexture = null;
  43166. /**
  43167. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43168. */
  43169. _this._forceIrradianceInFragment = false;
  43170. /**
  43171. * Force normal to face away from face.
  43172. */
  43173. _this._forceNormalForward = false;
  43174. /**
  43175. * Enables specular anti aliasing in the PBR shader.
  43176. * It will both interacts on the Geometry for analytical and IBL lighting.
  43177. * It also prefilter the roughness map based on the bump values.
  43178. */
  43179. _this._enableSpecularAntiAliasing = false;
  43180. /**
  43181. * Stores the available render targets.
  43182. */
  43183. _this._renderTargets = new BABYLON.SmartArray(16);
  43184. /**
  43185. * Sets the global ambient color for the material used in lighting calculations.
  43186. */
  43187. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43188. /**
  43189. * If set to true, no lighting calculations will be applied.
  43190. */
  43191. _this._unlit = false;
  43192. // Setup the default processing configuration to the scene.
  43193. _this._attachImageProcessingConfiguration(null);
  43194. _this.getRenderTargetTextures = function () {
  43195. _this._renderTargets.reset();
  43196. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43197. _this._renderTargets.push(_this._reflectionTexture);
  43198. }
  43199. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43200. _this._renderTargets.push(_this._refractionTexture);
  43201. }
  43202. return _this._renderTargets;
  43203. };
  43204. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43205. return _this;
  43206. }
  43207. /**
  43208. * Attaches a new image processing configuration to the PBR Material.
  43209. * @param configuration
  43210. */
  43211. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43212. var _this = this;
  43213. if (configuration === this._imageProcessingConfiguration) {
  43214. return;
  43215. }
  43216. // Detaches observer.
  43217. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43218. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43219. }
  43220. // Pick the scene configuration if needed.
  43221. if (!configuration) {
  43222. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43223. }
  43224. else {
  43225. this._imageProcessingConfiguration = configuration;
  43226. }
  43227. // Attaches observer.
  43228. if (this._imageProcessingConfiguration) {
  43229. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43230. _this._markAllSubMeshesAsImageProcessingDirty();
  43231. });
  43232. }
  43233. };
  43234. /**
  43235. * Gets the name of the material class.
  43236. */
  43237. PBRBaseMaterial.prototype.getClassName = function () {
  43238. return "PBRBaseMaterial";
  43239. };
  43240. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43241. /**
  43242. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43243. */
  43244. get: function () {
  43245. return this._useLogarithmicDepth;
  43246. },
  43247. /**
  43248. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43249. */
  43250. set: function (value) {
  43251. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43252. },
  43253. enumerable: true,
  43254. configurable: true
  43255. });
  43256. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43257. /**
  43258. * Gets the current transparency mode.
  43259. */
  43260. get: function () {
  43261. return this._transparencyMode;
  43262. },
  43263. /**
  43264. * Sets the transparency mode of the material.
  43265. *
  43266. * | Value | Type | Description |
  43267. * | ----- | ----------------------------------- | ----------- |
  43268. * | 0 | OPAQUE | |
  43269. * | 1 | ALPHATEST | |
  43270. * | 2 | ALPHABLEND | |
  43271. * | 3 | ALPHATESTANDBLEND | |
  43272. *
  43273. */
  43274. set: function (value) {
  43275. if (this._transparencyMode === value) {
  43276. return;
  43277. }
  43278. this._transparencyMode = value;
  43279. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43280. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43281. },
  43282. enumerable: true,
  43283. configurable: true
  43284. });
  43285. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43286. /**
  43287. * Returns true if alpha blending should be disabled.
  43288. */
  43289. get: function () {
  43290. return (this._linkRefractionWithTransparency ||
  43291. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43292. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43293. },
  43294. enumerable: true,
  43295. configurable: true
  43296. });
  43297. /**
  43298. * Specifies whether or not this material should be rendered in alpha blend mode.
  43299. */
  43300. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43301. if (this._disableAlphaBlending) {
  43302. return false;
  43303. }
  43304. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43305. };
  43306. /**
  43307. * Specifies if the mesh will require alpha blending.
  43308. * @param mesh - BJS mesh.
  43309. */
  43310. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43311. if (this._disableAlphaBlending) {
  43312. return false;
  43313. }
  43314. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43315. };
  43316. /**
  43317. * Specifies whether or not this material should be rendered in alpha test mode.
  43318. */
  43319. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43320. if (this._forceAlphaTest) {
  43321. return true;
  43322. }
  43323. if (this._linkRefractionWithTransparency) {
  43324. return false;
  43325. }
  43326. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43327. };
  43328. /**
  43329. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43330. */
  43331. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43332. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43333. };
  43334. /**
  43335. * Gets the texture used for the alpha test.
  43336. */
  43337. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43338. return this._albedoTexture;
  43339. };
  43340. /**
  43341. * Specifies that the submesh is ready to be used.
  43342. * @param mesh - BJS mesh.
  43343. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43344. * @param useInstances - Specifies that instances should be used.
  43345. * @returns - boolean indicating that the submesh is ready or not.
  43346. */
  43347. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43348. if (subMesh.effect && this.isFrozen) {
  43349. if (this._wasPreviouslyReady) {
  43350. return true;
  43351. }
  43352. }
  43353. if (!subMesh._materialDefines) {
  43354. subMesh._materialDefines = new PBRMaterialDefines();
  43355. }
  43356. var defines = subMesh._materialDefines;
  43357. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43358. if (defines._renderId === this.getScene().getRenderId()) {
  43359. return true;
  43360. }
  43361. }
  43362. var scene = this.getScene();
  43363. var engine = scene.getEngine();
  43364. if (defines._areTexturesDirty) {
  43365. if (scene.texturesEnabled) {
  43366. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43367. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43368. return false;
  43369. }
  43370. }
  43371. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43372. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43373. return false;
  43374. }
  43375. }
  43376. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43377. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43378. return false;
  43379. }
  43380. }
  43381. var reflectionTexture = this._getReflectionTexture();
  43382. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43383. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43384. return false;
  43385. }
  43386. }
  43387. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43388. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43389. return false;
  43390. }
  43391. }
  43392. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43393. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43394. return false;
  43395. }
  43396. }
  43397. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43398. if (this._metallicTexture) {
  43399. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43400. return false;
  43401. }
  43402. }
  43403. else if (this._reflectivityTexture) {
  43404. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43405. return false;
  43406. }
  43407. }
  43408. if (this._microSurfaceTexture) {
  43409. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43410. return false;
  43411. }
  43412. }
  43413. }
  43414. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43415. // Bump texture cannot be not blocking.
  43416. if (!this._bumpTexture.isReady()) {
  43417. return false;
  43418. }
  43419. }
  43420. var refractionTexture = this._getRefractionTexture();
  43421. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43422. if (!refractionTexture.isReadyOrNotBlocking()) {
  43423. return false;
  43424. }
  43425. }
  43426. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43427. // This is blocking.
  43428. if (!this._environmentBRDFTexture.isReady()) {
  43429. return false;
  43430. }
  43431. }
  43432. }
  43433. }
  43434. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43435. if (!this._imageProcessingConfiguration.isReady()) {
  43436. return false;
  43437. }
  43438. }
  43439. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43440. mesh.createNormals(true);
  43441. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43442. }
  43443. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43444. if (effect) {
  43445. scene.resetCachedMaterial();
  43446. subMesh.setEffect(effect, defines);
  43447. this.buildUniformLayout();
  43448. }
  43449. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43450. return false;
  43451. }
  43452. defines._renderId = scene.getRenderId();
  43453. this._wasPreviouslyReady = true;
  43454. return true;
  43455. };
  43456. /**
  43457. * Specifies if the material uses metallic roughness workflow.
  43458. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43459. */
  43460. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43461. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43462. return true;
  43463. }
  43464. return false;
  43465. };
  43466. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43467. if (onCompiled === void 0) { onCompiled = null; }
  43468. if (onError === void 0) { onError = null; }
  43469. if (useInstances === void 0) { useInstances = null; }
  43470. if (useClipPlane === void 0) { useClipPlane = null; }
  43471. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43472. if (!defines.isDirty) {
  43473. return null;
  43474. }
  43475. defines.markAsProcessed();
  43476. var scene = this.getScene();
  43477. var engine = scene.getEngine();
  43478. // Fallbacks
  43479. var fallbacks = new BABYLON.EffectFallbacks();
  43480. var fallbackRank = 0;
  43481. if (defines.USESPHERICALINVERTEX) {
  43482. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43483. }
  43484. if (defines.FOG) {
  43485. fallbacks.addFallback(fallbackRank, "FOG");
  43486. }
  43487. if (defines.SPECULARAA) {
  43488. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43489. }
  43490. if (defines.POINTSIZE) {
  43491. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43492. }
  43493. if (defines.LOGARITHMICDEPTH) {
  43494. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43495. }
  43496. if (defines.PARALLAX) {
  43497. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43498. }
  43499. if (defines.PARALLAXOCCLUSION) {
  43500. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43501. }
  43502. if (defines.ENVIRONMENTBRDF) {
  43503. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43504. }
  43505. if (defines.TANGENT) {
  43506. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43507. }
  43508. if (defines.BUMP) {
  43509. fallbacks.addFallback(fallbackRank++, "BUMP");
  43510. }
  43511. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43512. if (defines.SPECULARTERM) {
  43513. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43514. }
  43515. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43516. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43517. }
  43518. if (defines.LIGHTMAP) {
  43519. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43520. }
  43521. if (defines.NORMAL) {
  43522. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43523. }
  43524. if (defines.AMBIENT) {
  43525. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43526. }
  43527. if (defines.EMISSIVE) {
  43528. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43529. }
  43530. if (defines.VERTEXCOLOR) {
  43531. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43532. }
  43533. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43534. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43535. }
  43536. if (defines.MORPHTARGETS) {
  43537. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43538. }
  43539. //Attributes
  43540. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43541. if (defines.NORMAL) {
  43542. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43543. }
  43544. if (defines.TANGENT) {
  43545. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43546. }
  43547. if (defines.UV1) {
  43548. attribs.push(BABYLON.VertexBuffer.UVKind);
  43549. }
  43550. if (defines.UV2) {
  43551. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43552. }
  43553. if (defines.VERTEXCOLOR) {
  43554. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43555. }
  43556. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43557. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43558. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43559. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43560. "vFogInfos", "vFogColor", "pointSize",
  43561. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43562. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43563. "mBones",
  43564. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43565. "vLightingIntensity",
  43566. "logarithmicDepthConstant",
  43567. "vSphericalX", "vSphericalY", "vSphericalZ",
  43568. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43569. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43570. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43571. "vTangentSpaceParams"
  43572. ];
  43573. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43574. "bumpSampler", "lightmapSampler", "opacitySampler",
  43575. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43576. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43577. "microSurfaceSampler", "environmentBrdfSampler"];
  43578. var uniformBuffers = ["Material", "Scene"];
  43579. if (BABYLON.ImageProcessingConfiguration) {
  43580. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43581. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43582. }
  43583. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43584. uniformsNames: uniforms,
  43585. uniformBuffersNames: uniformBuffers,
  43586. samplers: samplers,
  43587. defines: defines,
  43588. maxSimultaneousLights: this._maxSimultaneousLights
  43589. });
  43590. var join = defines.toString();
  43591. return engine.createEffect("pbr", {
  43592. attributes: attribs,
  43593. uniformsNames: uniforms,
  43594. uniformBuffersNames: uniformBuffers,
  43595. samplers: samplers,
  43596. defines: join,
  43597. fallbacks: fallbacks,
  43598. onCompiled: onCompiled,
  43599. onError: onError,
  43600. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43601. }, engine);
  43602. };
  43603. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43604. if (useInstances === void 0) { useInstances = null; }
  43605. if (useClipPlane === void 0) { useClipPlane = null; }
  43606. var scene = this.getScene();
  43607. var engine = scene.getEngine();
  43608. // Lights
  43609. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43610. defines._needNormals = true;
  43611. // Textures
  43612. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43613. if (defines._areTexturesDirty) {
  43614. defines._needUVs = false;
  43615. if (scene.texturesEnabled) {
  43616. if (scene.getEngine().getCaps().textureLOD) {
  43617. defines.LODBASEDMICROSFURACE = true;
  43618. }
  43619. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43620. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43621. }
  43622. else {
  43623. defines.ALBEDO = false;
  43624. }
  43625. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43626. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43627. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43628. }
  43629. else {
  43630. defines.AMBIENT = false;
  43631. }
  43632. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43633. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43634. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43635. }
  43636. else {
  43637. defines.OPACITY = false;
  43638. }
  43639. var reflectionTexture = this._getReflectionTexture();
  43640. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43641. defines.REFLECTION = true;
  43642. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43643. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43644. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43645. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43646. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43647. defines.INVERTCUBICMAP = true;
  43648. }
  43649. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43650. switch (reflectionTexture.coordinatesMode) {
  43651. case BABYLON.Texture.EXPLICIT_MODE:
  43652. defines.REFLECTIONMAP_EXPLICIT = true;
  43653. break;
  43654. case BABYLON.Texture.PLANAR_MODE:
  43655. defines.REFLECTIONMAP_PLANAR = true;
  43656. break;
  43657. case BABYLON.Texture.PROJECTION_MODE:
  43658. defines.REFLECTIONMAP_PROJECTION = true;
  43659. break;
  43660. case BABYLON.Texture.SKYBOX_MODE:
  43661. defines.REFLECTIONMAP_SKYBOX = true;
  43662. break;
  43663. case BABYLON.Texture.SPHERICAL_MODE:
  43664. defines.REFLECTIONMAP_SPHERICAL = true;
  43665. break;
  43666. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43667. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43668. break;
  43669. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43670. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43671. break;
  43672. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43673. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43674. break;
  43675. case BABYLON.Texture.CUBIC_MODE:
  43676. case BABYLON.Texture.INVCUBIC_MODE:
  43677. default:
  43678. defines.REFLECTIONMAP_CUBIC = true;
  43679. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43680. break;
  43681. }
  43682. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43683. if (reflectionTexture.sphericalPolynomial) {
  43684. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43685. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43686. defines.USESPHERICALINVERTEX = false;
  43687. }
  43688. else {
  43689. defines.USESPHERICALINVERTEX = true;
  43690. }
  43691. }
  43692. }
  43693. }
  43694. else {
  43695. defines.REFLECTION = false;
  43696. defines.REFLECTIONMAP_3D = false;
  43697. defines.REFLECTIONMAP_SPHERICAL = false;
  43698. defines.REFLECTIONMAP_PLANAR = false;
  43699. defines.REFLECTIONMAP_CUBIC = false;
  43700. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43701. defines.REFLECTIONMAP_PROJECTION = false;
  43702. defines.REFLECTIONMAP_SKYBOX = false;
  43703. defines.REFLECTIONMAP_EXPLICIT = false;
  43704. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43705. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43706. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43707. defines.INVERTCUBICMAP = false;
  43708. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43709. defines.USESPHERICALINVERTEX = false;
  43710. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43711. defines.LODINREFLECTIONALPHA = false;
  43712. defines.GAMMAREFLECTION = false;
  43713. defines.RGBDREFLECTION = false;
  43714. }
  43715. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43716. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43717. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43718. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43719. }
  43720. else {
  43721. defines.LIGHTMAP = false;
  43722. }
  43723. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43724. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43725. }
  43726. else {
  43727. defines.EMISSIVE = false;
  43728. }
  43729. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43730. if (this._metallicTexture) {
  43731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43732. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43733. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43734. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43735. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43736. }
  43737. else if (this._reflectivityTexture) {
  43738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43739. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43740. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43741. }
  43742. else {
  43743. defines.REFLECTIVITY = false;
  43744. }
  43745. if (this._microSurfaceTexture) {
  43746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  43747. }
  43748. else {
  43749. defines.MICROSURFACEMAP = false;
  43750. }
  43751. }
  43752. else {
  43753. defines.REFLECTIVITY = false;
  43754. defines.MICROSURFACEMAP = false;
  43755. }
  43756. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43758. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43759. defines.PARALLAX = true;
  43760. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  43761. }
  43762. else {
  43763. defines.PARALLAX = false;
  43764. }
  43765. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43766. }
  43767. else {
  43768. defines.BUMP = false;
  43769. }
  43770. var refractionTexture = this._getRefractionTexture();
  43771. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43772. defines.REFRACTION = true;
  43773. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  43774. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  43775. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  43776. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  43777. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  43778. if (this._linkRefractionWithTransparency) {
  43779. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  43780. }
  43781. }
  43782. else {
  43783. defines.REFRACTION = false;
  43784. }
  43785. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43786. defines.ENVIRONMENTBRDF = true;
  43787. }
  43788. else {
  43789. defines.ENVIRONMENTBRDF = false;
  43790. }
  43791. if (this._shouldUseAlphaFromAlbedoTexture()) {
  43792. defines.ALPHAFROMALBEDO = true;
  43793. }
  43794. else {
  43795. defines.ALPHAFROMALBEDO = false;
  43796. }
  43797. }
  43798. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43799. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  43800. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  43801. if (!this.backFaceCulling && this._twoSidedLighting) {
  43802. defines.TWOSIDEDLIGHTING = true;
  43803. }
  43804. else {
  43805. defines.TWOSIDEDLIGHTING = false;
  43806. }
  43807. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  43808. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43809. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  43810. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  43811. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  43812. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  43813. }
  43814. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43815. this._imageProcessingConfiguration.prepareDefines(defines);
  43816. }
  43817. defines.FORCENORMALFORWARD = this._forceNormalForward;
  43818. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  43819. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  43820. // Misc.
  43821. if (defines._areMiscDirty) {
  43822. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  43823. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  43824. }
  43825. // Values that need to be evaluated on every frame
  43826. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  43827. // Attribs
  43828. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  43829. };
  43830. /**
  43831. * Force shader compilation
  43832. */
  43833. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  43834. var _this = this;
  43835. var localOptions = __assign({ clipPlane: false }, options);
  43836. var defines = new PBRMaterialDefines();
  43837. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  43838. if (effect.isReady()) {
  43839. if (onCompiled) {
  43840. onCompiled(this);
  43841. }
  43842. }
  43843. else {
  43844. effect.onCompileObservable.add(function () {
  43845. if (onCompiled) {
  43846. onCompiled(_this);
  43847. }
  43848. });
  43849. }
  43850. };
  43851. /**
  43852. * Initializes the uniform buffer layout for the shader.
  43853. */
  43854. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  43855. // Order is important !
  43856. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  43857. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  43858. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43859. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43860. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43861. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  43862. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  43863. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43864. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43865. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43866. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43867. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43868. this._uniformBuffer.addUniform("albedoMatrix", 16);
  43869. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43870. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43871. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43872. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43873. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  43874. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  43875. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43876. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43877. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43878. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43879. this._uniformBuffer.addUniform("vReflectionColor", 3);
  43880. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  43881. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  43882. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  43883. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  43884. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  43885. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43886. this._uniformBuffer.addUniform("pointSize", 1);
  43887. this._uniformBuffer.create();
  43888. };
  43889. /**
  43890. * Unbinds the textures.
  43891. */
  43892. PBRBaseMaterial.prototype.unbind = function () {
  43893. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43894. this._uniformBuffer.setTexture("reflectionSampler", null);
  43895. }
  43896. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43897. this._uniformBuffer.setTexture("refractionSampler", null);
  43898. }
  43899. _super.prototype.unbind.call(this);
  43900. };
  43901. /**
  43902. * Binds the submesh data.
  43903. * @param world - The world matrix.
  43904. * @param mesh - The BJS mesh.
  43905. * @param subMesh - A submesh of the BJS mesh.
  43906. */
  43907. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43908. var scene = this.getScene();
  43909. var defines = subMesh._materialDefines;
  43910. if (!defines) {
  43911. return;
  43912. }
  43913. var effect = subMesh.effect;
  43914. if (!effect) {
  43915. return;
  43916. }
  43917. this._activeEffect = effect;
  43918. // Matrices
  43919. this.bindOnlyWorldMatrix(world);
  43920. // Normal Matrix
  43921. if (defines.OBJECTSPACE_NORMALMAP) {
  43922. world.toNormalMatrix(this._normalMatrix);
  43923. this.bindOnlyNormalMatrix(this._normalMatrix);
  43924. }
  43925. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43926. // Bones
  43927. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  43928. var reflectionTexture = null;
  43929. if (mustRebind) {
  43930. this._uniformBuffer.bindToEffect(effect, "Material");
  43931. this.bindViewProjection(effect);
  43932. reflectionTexture = this._getReflectionTexture();
  43933. var refractionTexture = this._getRefractionTexture();
  43934. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43935. // Texture uniforms
  43936. if (scene.texturesEnabled) {
  43937. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43938. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  43939. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  43940. }
  43941. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43942. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  43943. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43944. }
  43945. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43946. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43947. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43948. }
  43949. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43950. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  43951. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  43952. if (reflectionTexture.boundingBoxSize) {
  43953. var cubeTexture = reflectionTexture;
  43954. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43955. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43956. }
  43957. var polynomials = reflectionTexture.sphericalPolynomial;
  43958. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  43959. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  43960. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  43961. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  43962. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  43963. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  43964. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  43965. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  43966. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  43967. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  43968. }
  43969. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  43970. }
  43971. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43972. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43973. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43974. }
  43975. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43976. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43977. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43978. }
  43979. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43980. if (this._metallicTexture) {
  43981. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  43982. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  43983. }
  43984. else if (this._reflectivityTexture) {
  43985. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  43986. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  43987. }
  43988. if (this._microSurfaceTexture) {
  43989. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  43990. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  43991. }
  43992. }
  43993. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43994. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  43995. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43996. if (scene._mirroredCameraPosition) {
  43997. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43998. }
  43999. else {
  44000. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44001. }
  44002. }
  44003. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44004. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44005. var depth = 1.0;
  44006. if (!refractionTexture.isCube) {
  44007. if (refractionTexture.depth) {
  44008. depth = refractionTexture.depth;
  44009. }
  44010. }
  44011. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44012. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44013. }
  44014. }
  44015. // Point size
  44016. if (this.pointsCloud) {
  44017. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44018. }
  44019. // Colors
  44020. if (defines.METALLICWORKFLOW) {
  44021. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44022. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44023. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44024. }
  44025. else {
  44026. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44027. }
  44028. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44029. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44030. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44031. // Misc
  44032. this._lightingInfos.x = this._directIntensity;
  44033. this._lightingInfos.y = this._emissiveIntensity;
  44034. this._lightingInfos.z = this._environmentIntensity;
  44035. this._lightingInfos.w = this._specularIntensity;
  44036. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44037. }
  44038. // Textures
  44039. if (scene.texturesEnabled) {
  44040. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44041. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44042. }
  44043. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44044. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44045. }
  44046. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44047. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44048. }
  44049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44050. if (defines.LODBASEDMICROSFURACE) {
  44051. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44052. }
  44053. else {
  44054. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44055. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44056. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44057. }
  44058. }
  44059. if (defines.ENVIRONMENTBRDF) {
  44060. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44061. }
  44062. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44063. if (defines.LODBASEDMICROSFURACE) {
  44064. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44065. }
  44066. else {
  44067. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44068. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44069. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44070. }
  44071. }
  44072. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44073. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44074. }
  44075. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44076. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44077. }
  44078. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44079. if (this._metallicTexture) {
  44080. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44081. }
  44082. else if (this._reflectivityTexture) {
  44083. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44084. }
  44085. if (this._microSurfaceTexture) {
  44086. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44087. }
  44088. }
  44089. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44090. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44091. }
  44092. }
  44093. // Clip plane
  44094. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44095. // Colors
  44096. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44097. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44098. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44099. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44100. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44101. }
  44102. if (mustRebind || !this.isFrozen) {
  44103. // Lights
  44104. if (scene.lightsEnabled && !this._disableLighting) {
  44105. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44106. }
  44107. // View
  44108. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44109. this.bindView(effect);
  44110. }
  44111. // Fog
  44112. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44113. // Morph targets
  44114. if (defines.NUM_MORPH_INFLUENCERS) {
  44115. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44116. }
  44117. // image processing
  44118. this._imageProcessingConfiguration.bind(this._activeEffect);
  44119. // Log. depth
  44120. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44121. }
  44122. this._uniformBuffer.update();
  44123. this._afterBind(mesh, this._activeEffect);
  44124. };
  44125. /**
  44126. * Returns the animatable textures.
  44127. * @returns - Array of animatable textures.
  44128. */
  44129. PBRBaseMaterial.prototype.getAnimatables = function () {
  44130. var results = [];
  44131. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44132. results.push(this._albedoTexture);
  44133. }
  44134. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44135. results.push(this._ambientTexture);
  44136. }
  44137. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44138. results.push(this._opacityTexture);
  44139. }
  44140. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44141. results.push(this._reflectionTexture);
  44142. }
  44143. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44144. results.push(this._emissiveTexture);
  44145. }
  44146. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44147. results.push(this._metallicTexture);
  44148. }
  44149. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44150. results.push(this._reflectivityTexture);
  44151. }
  44152. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44153. results.push(this._bumpTexture);
  44154. }
  44155. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44156. results.push(this._lightmapTexture);
  44157. }
  44158. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44159. results.push(this._refractionTexture);
  44160. }
  44161. return results;
  44162. };
  44163. /**
  44164. * Returns the texture used for reflections.
  44165. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44166. */
  44167. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44168. if (this._reflectionTexture) {
  44169. return this._reflectionTexture;
  44170. }
  44171. return this.getScene().environmentTexture;
  44172. };
  44173. /**
  44174. * Returns the texture used for refraction or null if none is used.
  44175. * @returns - Refection texture if present. If no refraction texture and refraction
  44176. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44177. */
  44178. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44179. if (this._refractionTexture) {
  44180. return this._refractionTexture;
  44181. }
  44182. if (this._linkRefractionWithTransparency) {
  44183. return this.getScene().environmentTexture;
  44184. }
  44185. return null;
  44186. };
  44187. /**
  44188. * Disposes the resources of the material.
  44189. * @param forceDisposeEffect - Forces the disposal of effects.
  44190. * @param forceDisposeTextures - Forces the disposal of all textures.
  44191. */
  44192. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44193. if (forceDisposeTextures) {
  44194. if (this._albedoTexture) {
  44195. this._albedoTexture.dispose();
  44196. }
  44197. if (this._ambientTexture) {
  44198. this._ambientTexture.dispose();
  44199. }
  44200. if (this._opacityTexture) {
  44201. this._opacityTexture.dispose();
  44202. }
  44203. if (this._reflectionTexture) {
  44204. this._reflectionTexture.dispose();
  44205. }
  44206. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44207. this._environmentBRDFTexture.dispose();
  44208. }
  44209. if (this._emissiveTexture) {
  44210. this._emissiveTexture.dispose();
  44211. }
  44212. if (this._metallicTexture) {
  44213. this._metallicTexture.dispose();
  44214. }
  44215. if (this._reflectivityTexture) {
  44216. this._reflectivityTexture.dispose();
  44217. }
  44218. if (this._bumpTexture) {
  44219. this._bumpTexture.dispose();
  44220. }
  44221. if (this._lightmapTexture) {
  44222. this._lightmapTexture.dispose();
  44223. }
  44224. if (this._refractionTexture) {
  44225. this._refractionTexture.dispose();
  44226. }
  44227. }
  44228. this._renderTargets.dispose();
  44229. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44230. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44231. }
  44232. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44233. };
  44234. /**
  44235. * Stores the reflectivity values based on metallic roughness workflow.
  44236. */
  44237. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44238. __decorate([
  44239. BABYLON.serializeAsImageProcessingConfiguration()
  44240. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44241. __decorate([
  44242. BABYLON.serialize()
  44243. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44244. __decorate([
  44245. BABYLON.serialize()
  44246. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44247. return PBRBaseMaterial;
  44248. }(BABYLON.PushMaterial));
  44249. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44250. })(BABYLON || (BABYLON = {}));
  44251. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44252. var BABYLON;
  44253. (function (BABYLON) {
  44254. /**
  44255. * The Physically based simple base material of BJS.
  44256. *
  44257. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44258. * It is used as the base class for both the specGloss and metalRough conventions.
  44259. */
  44260. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44261. __extends(PBRBaseSimpleMaterial, _super);
  44262. /**
  44263. * Instantiates a new PBRMaterial instance.
  44264. *
  44265. * @param name The material name
  44266. * @param scene The scene the material will be use in.
  44267. */
  44268. function PBRBaseSimpleMaterial(name, scene) {
  44269. var _this = _super.call(this, name, scene) || this;
  44270. /**
  44271. * Number of Simultaneous lights allowed on the material.
  44272. */
  44273. _this.maxSimultaneousLights = 4;
  44274. /**
  44275. * If sets to true, disables all the lights affecting the material.
  44276. */
  44277. _this.disableLighting = false;
  44278. /**
  44279. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44280. */
  44281. _this.invertNormalMapX = false;
  44282. /**
  44283. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44284. */
  44285. _this.invertNormalMapY = false;
  44286. /**
  44287. * Emissivie color used to self-illuminate the model.
  44288. */
  44289. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44290. /**
  44291. * Occlusion Channel Strenght.
  44292. */
  44293. _this.occlusionStrength = 1.0;
  44294. _this.useLightmapAsShadowmap = false;
  44295. _this._useAlphaFromAlbedoTexture = true;
  44296. _this._useAmbientInGrayScale = true;
  44297. return _this;
  44298. }
  44299. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44300. /**
  44301. * Gets the current double sided mode.
  44302. */
  44303. get: function () {
  44304. return this._twoSidedLighting;
  44305. },
  44306. /**
  44307. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44308. */
  44309. set: function (value) {
  44310. if (this._twoSidedLighting === value) {
  44311. return;
  44312. }
  44313. this._twoSidedLighting = value;
  44314. this.backFaceCulling = !value;
  44315. this._markAllSubMeshesAsTexturesDirty();
  44316. },
  44317. enumerable: true,
  44318. configurable: true
  44319. });
  44320. /**
  44321. * Return the active textures of the material.
  44322. */
  44323. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44324. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44325. if (this.environmentTexture) {
  44326. activeTextures.push(this.environmentTexture);
  44327. }
  44328. if (this.normalTexture) {
  44329. activeTextures.push(this.normalTexture);
  44330. }
  44331. if (this.emissiveTexture) {
  44332. activeTextures.push(this.emissiveTexture);
  44333. }
  44334. if (this.occlusionTexture) {
  44335. activeTextures.push(this.occlusionTexture);
  44336. }
  44337. if (this.lightmapTexture) {
  44338. activeTextures.push(this.lightmapTexture);
  44339. }
  44340. return activeTextures;
  44341. };
  44342. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44343. if (_super.prototype.hasTexture.call(this, texture)) {
  44344. return true;
  44345. }
  44346. if (this.lightmapTexture === texture) {
  44347. return true;
  44348. }
  44349. return false;
  44350. };
  44351. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44352. return "PBRBaseSimpleMaterial";
  44353. };
  44354. __decorate([
  44355. BABYLON.serialize(),
  44356. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44357. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44358. __decorate([
  44359. BABYLON.serialize(),
  44360. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44361. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44362. __decorate([
  44363. BABYLON.serializeAsTexture(),
  44364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44365. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44366. __decorate([
  44367. BABYLON.serialize(),
  44368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44369. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44370. __decorate([
  44371. BABYLON.serialize(),
  44372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44373. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44374. __decorate([
  44375. BABYLON.serializeAsTexture(),
  44376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44377. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44378. __decorate([
  44379. BABYLON.serializeAsColor3("emissive"),
  44380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44381. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44382. __decorate([
  44383. BABYLON.serializeAsTexture(),
  44384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44385. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44386. __decorate([
  44387. BABYLON.serialize(),
  44388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44389. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44390. __decorate([
  44391. BABYLON.serializeAsTexture(),
  44392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44393. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44394. __decorate([
  44395. BABYLON.serialize(),
  44396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44397. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44398. __decorate([
  44399. BABYLON.serialize()
  44400. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44401. __decorate([
  44402. BABYLON.serializeAsTexture(),
  44403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44404. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44405. __decorate([
  44406. BABYLON.serialize(),
  44407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44408. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44409. return PBRBaseSimpleMaterial;
  44410. }(BABYLON.PBRBaseMaterial));
  44411. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44412. })(BABYLON || (BABYLON = {}));
  44413. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44414. var BABYLON;
  44415. (function (BABYLON) {
  44416. /**
  44417. * The Physically based material of BJS.
  44418. *
  44419. * This offers the main features of a standard PBR material.
  44420. * For more information, please refer to the documentation :
  44421. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44422. */
  44423. var PBRMaterial = /** @class */ (function (_super) {
  44424. __extends(PBRMaterial, _super);
  44425. /**
  44426. * Instantiates a new PBRMaterial instance.
  44427. *
  44428. * @param name The material name
  44429. * @param scene The scene the material will be use in.
  44430. */
  44431. function PBRMaterial(name, scene) {
  44432. var _this = _super.call(this, name, scene) || this;
  44433. /**
  44434. * Intensity of the direct lights e.g. the four lights available in your scene.
  44435. * This impacts both the direct diffuse and specular highlights.
  44436. */
  44437. _this.directIntensity = 1.0;
  44438. /**
  44439. * Intensity of the emissive part of the material.
  44440. * This helps controlling the emissive effect without modifying the emissive color.
  44441. */
  44442. _this.emissiveIntensity = 1.0;
  44443. /**
  44444. * Intensity of the environment e.g. how much the environment will light the object
  44445. * either through harmonics for rough material or through the refelction for shiny ones.
  44446. */
  44447. _this.environmentIntensity = 1.0;
  44448. /**
  44449. * This is a special control allowing the reduction of the specular highlights coming from the
  44450. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44451. */
  44452. _this.specularIntensity = 1.0;
  44453. /**
  44454. * Debug Control allowing disabling the bump map on this material.
  44455. */
  44456. _this.disableBumpMap = false;
  44457. /**
  44458. * AKA Occlusion Texture Intensity in other nomenclature.
  44459. */
  44460. _this.ambientTextureStrength = 1.0;
  44461. /**
  44462. * The color of a material in ambient lighting.
  44463. */
  44464. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44465. /**
  44466. * AKA Diffuse Color in other nomenclature.
  44467. */
  44468. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44469. /**
  44470. * AKA Specular Color in other nomenclature.
  44471. */
  44472. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44473. /**
  44474. * The color reflected from the material.
  44475. */
  44476. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44477. /**
  44478. * The color emitted from the material.
  44479. */
  44480. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44481. /**
  44482. * AKA Glossiness in other nomenclature.
  44483. */
  44484. _this.microSurface = 1.0;
  44485. /**
  44486. * source material index of refraction (IOR)' / 'destination material IOR.
  44487. */
  44488. _this.indexOfRefraction = 0.66;
  44489. /**
  44490. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44491. */
  44492. _this.invertRefractionY = false;
  44493. /**
  44494. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44495. * Materials half opaque for instance using refraction could benefit from this control.
  44496. */
  44497. _this.linkRefractionWithTransparency = false;
  44498. _this.useLightmapAsShadowmap = false;
  44499. /**
  44500. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44501. */
  44502. _this.useAlphaFromAlbedoTexture = false;
  44503. /**
  44504. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44505. */
  44506. _this.forceAlphaTest = false;
  44507. /**
  44508. * Defines the alpha limits in alpha test mode.
  44509. */
  44510. _this.alphaCutOff = 0.4;
  44511. /**
  44512. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44513. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44514. */
  44515. _this.useSpecularOverAlpha = true;
  44516. /**
  44517. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44518. */
  44519. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44520. /**
  44521. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44522. */
  44523. _this.useRoughnessFromMetallicTextureAlpha = true;
  44524. /**
  44525. * Specifies if the metallic texture contains the roughness information in its green channel.
  44526. */
  44527. _this.useRoughnessFromMetallicTextureGreen = false;
  44528. /**
  44529. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44530. */
  44531. _this.useMetallnessFromMetallicTextureBlue = false;
  44532. /**
  44533. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44534. */
  44535. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44536. /**
  44537. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44538. */
  44539. _this.useAmbientInGrayScale = false;
  44540. /**
  44541. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44542. * The material will try to infer what glossiness each pixel should be.
  44543. */
  44544. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44545. /**
  44546. * BJS is using an harcoded light falloff based on a manually sets up range.
  44547. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44548. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44549. */
  44550. _this.usePhysicalLightFalloff = true;
  44551. /**
  44552. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44553. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44554. */
  44555. _this.useRadianceOverAlpha = true;
  44556. /**
  44557. * Allows using an object space normal map (instead of tangent space).
  44558. */
  44559. _this.useObjectSpaceNormalMap = false;
  44560. /**
  44561. * Allows using the bump map in parallax mode.
  44562. */
  44563. _this.useParallax = false;
  44564. /**
  44565. * Allows using the bump map in parallax occlusion mode.
  44566. */
  44567. _this.useParallaxOcclusion = false;
  44568. /**
  44569. * Controls the scale bias of the parallax mode.
  44570. */
  44571. _this.parallaxScaleBias = 0.05;
  44572. /**
  44573. * If sets to true, disables all the lights affecting the material.
  44574. */
  44575. _this.disableLighting = false;
  44576. /**
  44577. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44578. */
  44579. _this.forceIrradianceInFragment = false;
  44580. /**
  44581. * Number of Simultaneous lights allowed on the material.
  44582. */
  44583. _this.maxSimultaneousLights = 4;
  44584. /**
  44585. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44586. */
  44587. _this.invertNormalMapX = false;
  44588. /**
  44589. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44590. */
  44591. _this.invertNormalMapY = false;
  44592. /**
  44593. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44594. */
  44595. _this.twoSidedLighting = false;
  44596. /**
  44597. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44598. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44599. */
  44600. _this.useAlphaFresnel = false;
  44601. /**
  44602. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44603. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44604. */
  44605. _this.useLinearAlphaFresnel = false;
  44606. /**
  44607. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44608. * And/Or occlude the blended part.
  44609. */
  44610. _this.environmentBRDFTexture = null;
  44611. /**
  44612. * Force normal to face away from face.
  44613. */
  44614. _this.forceNormalForward = false;
  44615. /**
  44616. * Enables specular anti aliasing in the PBR shader.
  44617. * It will both interacts on the Geometry for analytical and IBL lighting.
  44618. * It also prefilter the roughness map based on the bump values.
  44619. */
  44620. _this.enableSpecularAntiAliasing = false;
  44621. /**
  44622. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44623. * makes the reflect vector face the model (under horizon).
  44624. */
  44625. _this.useHorizonOcclusion = true;
  44626. /**
  44627. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44628. * too much the area relying on ambient texture to define their ambient occlusion.
  44629. */
  44630. _this.useRadianceOcclusion = true;
  44631. /**
  44632. * If set to true, no lighting calculations will be applied.
  44633. */
  44634. _this.unlit = false;
  44635. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44636. return _this;
  44637. }
  44638. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44639. /**
  44640. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44641. */
  44642. get: function () {
  44643. return this._PBRMATERIAL_OPAQUE;
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44649. /**
  44650. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44651. */
  44652. get: function () {
  44653. return this._PBRMATERIAL_ALPHATEST;
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44659. /**
  44660. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44661. */
  44662. get: function () {
  44663. return this._PBRMATERIAL_ALPHABLEND;
  44664. },
  44665. enumerable: true,
  44666. configurable: true
  44667. });
  44668. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44669. /**
  44670. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44671. * They are also discarded below the alpha cutoff threshold to improve performances.
  44672. */
  44673. get: function () {
  44674. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44675. },
  44676. enumerable: true,
  44677. configurable: true
  44678. });
  44679. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44680. /**
  44681. * Gets the image processing configuration used either in this material.
  44682. */
  44683. get: function () {
  44684. return this._imageProcessingConfiguration;
  44685. },
  44686. /**
  44687. * Sets the Default image processing configuration used either in the this material.
  44688. *
  44689. * If sets to null, the scene one is in use.
  44690. */
  44691. set: function (value) {
  44692. this._attachImageProcessingConfiguration(value);
  44693. // Ensure the effect will be rebuilt.
  44694. this._markAllSubMeshesAsTexturesDirty();
  44695. },
  44696. enumerable: true,
  44697. configurable: true
  44698. });
  44699. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44700. /**
  44701. * Gets wether the color curves effect is enabled.
  44702. */
  44703. get: function () {
  44704. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44705. },
  44706. /**
  44707. * Sets wether the color curves effect is enabled.
  44708. */
  44709. set: function (value) {
  44710. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  44711. },
  44712. enumerable: true,
  44713. configurable: true
  44714. });
  44715. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  44716. /**
  44717. * Gets wether the color grading effect is enabled.
  44718. */
  44719. get: function () {
  44720. return this.imageProcessingConfiguration.colorGradingEnabled;
  44721. },
  44722. /**
  44723. * Gets wether the color grading effect is enabled.
  44724. */
  44725. set: function (value) {
  44726. this.imageProcessingConfiguration.colorGradingEnabled = value;
  44727. },
  44728. enumerable: true,
  44729. configurable: true
  44730. });
  44731. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  44732. /**
  44733. * Gets wether tonemapping is enabled or not.
  44734. */
  44735. get: function () {
  44736. return this._imageProcessingConfiguration.toneMappingEnabled;
  44737. },
  44738. /**
  44739. * Sets wether tonemapping is enabled or not
  44740. */
  44741. set: function (value) {
  44742. this._imageProcessingConfiguration.toneMappingEnabled = value;
  44743. },
  44744. enumerable: true,
  44745. configurable: true
  44746. });
  44747. ;
  44748. ;
  44749. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  44750. /**
  44751. * The camera exposure used on this material.
  44752. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44753. * This corresponds to a photographic exposure.
  44754. */
  44755. get: function () {
  44756. return this._imageProcessingConfiguration.exposure;
  44757. },
  44758. /**
  44759. * The camera exposure used on this material.
  44760. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44761. * This corresponds to a photographic exposure.
  44762. */
  44763. set: function (value) {
  44764. this._imageProcessingConfiguration.exposure = value;
  44765. },
  44766. enumerable: true,
  44767. configurable: true
  44768. });
  44769. ;
  44770. ;
  44771. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  44772. /**
  44773. * Gets The camera contrast used on this material.
  44774. */
  44775. get: function () {
  44776. return this._imageProcessingConfiguration.contrast;
  44777. },
  44778. /**
  44779. * Sets The camera contrast used on this material.
  44780. */
  44781. set: function (value) {
  44782. this._imageProcessingConfiguration.contrast = value;
  44783. },
  44784. enumerable: true,
  44785. configurable: true
  44786. });
  44787. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  44788. /**
  44789. * Gets the Color Grading 2D Lookup Texture.
  44790. */
  44791. get: function () {
  44792. return this._imageProcessingConfiguration.colorGradingTexture;
  44793. },
  44794. /**
  44795. * Sets the Color Grading 2D Lookup Texture.
  44796. */
  44797. set: function (value) {
  44798. this._imageProcessingConfiguration.colorGradingTexture = value;
  44799. },
  44800. enumerable: true,
  44801. configurable: true
  44802. });
  44803. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  44804. /**
  44805. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44806. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44807. * 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;
  44808. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44809. */
  44810. get: function () {
  44811. return this._imageProcessingConfiguration.colorCurves;
  44812. },
  44813. /**
  44814. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  44815. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  44816. * 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;
  44817. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  44818. */
  44819. set: function (value) {
  44820. this._imageProcessingConfiguration.colorCurves = value;
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. /**
  44826. * Returns the name of this material class.
  44827. */
  44828. PBRMaterial.prototype.getClassName = function () {
  44829. return "PBRMaterial";
  44830. };
  44831. /**
  44832. * Returns an array of the actively used textures.
  44833. * @returns - Array of BaseTextures
  44834. */
  44835. PBRMaterial.prototype.getActiveTextures = function () {
  44836. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44837. if (this._albedoTexture) {
  44838. activeTextures.push(this._albedoTexture);
  44839. }
  44840. if (this._ambientTexture) {
  44841. activeTextures.push(this._ambientTexture);
  44842. }
  44843. if (this._opacityTexture) {
  44844. activeTextures.push(this._opacityTexture);
  44845. }
  44846. if (this._reflectionTexture) {
  44847. activeTextures.push(this._reflectionTexture);
  44848. }
  44849. if (this._emissiveTexture) {
  44850. activeTextures.push(this._emissiveTexture);
  44851. }
  44852. if (this._reflectivityTexture) {
  44853. activeTextures.push(this._reflectivityTexture);
  44854. }
  44855. if (this._metallicTexture) {
  44856. activeTextures.push(this._metallicTexture);
  44857. }
  44858. if (this._microSurfaceTexture) {
  44859. activeTextures.push(this._microSurfaceTexture);
  44860. }
  44861. if (this._bumpTexture) {
  44862. activeTextures.push(this._bumpTexture);
  44863. }
  44864. if (this._lightmapTexture) {
  44865. activeTextures.push(this._lightmapTexture);
  44866. }
  44867. if (this._refractionTexture) {
  44868. activeTextures.push(this._refractionTexture);
  44869. }
  44870. return activeTextures;
  44871. };
  44872. /**
  44873. * Checks to see if a texture is used in the material.
  44874. * @param texture - Base texture to use.
  44875. * @returns - Boolean specifying if a texture is used in the material.
  44876. */
  44877. PBRMaterial.prototype.hasTexture = function (texture) {
  44878. if (_super.prototype.hasTexture.call(this, texture)) {
  44879. return true;
  44880. }
  44881. if (this._albedoTexture === texture) {
  44882. return true;
  44883. }
  44884. if (this._ambientTexture === texture) {
  44885. return true;
  44886. }
  44887. if (this._opacityTexture === texture) {
  44888. return true;
  44889. }
  44890. if (this._reflectionTexture === texture) {
  44891. return true;
  44892. }
  44893. if (this._reflectivityTexture === texture) {
  44894. return true;
  44895. }
  44896. if (this._metallicTexture === texture) {
  44897. return true;
  44898. }
  44899. if (this._microSurfaceTexture === texture) {
  44900. return true;
  44901. }
  44902. if (this._bumpTexture === texture) {
  44903. return true;
  44904. }
  44905. if (this._lightmapTexture === texture) {
  44906. return true;
  44907. }
  44908. if (this._refractionTexture === texture) {
  44909. return true;
  44910. }
  44911. return false;
  44912. };
  44913. /**
  44914. * Makes a duplicate of the current material.
  44915. * @param name - name to use for the new material.
  44916. */
  44917. PBRMaterial.prototype.clone = function (name) {
  44918. var _this = this;
  44919. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  44920. clone.id = name;
  44921. clone.name = name;
  44922. return clone;
  44923. };
  44924. /**
  44925. * Serializes this PBR Material.
  44926. * @returns - An object with the serialized material.
  44927. */
  44928. PBRMaterial.prototype.serialize = function () {
  44929. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44930. serializationObject.customType = "BABYLON.PBRMaterial";
  44931. return serializationObject;
  44932. };
  44933. // Statics
  44934. /**
  44935. * Parses a PBR Material from a serialized object.
  44936. * @param source - Serialized object.
  44937. * @param scene - BJS scene instance.
  44938. * @param rootUrl - url for the scene object
  44939. * @returns - PBRMaterial
  44940. */
  44941. PBRMaterial.Parse = function (source, scene, rootUrl) {
  44942. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  44943. };
  44944. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  44945. /**
  44946. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44947. */
  44948. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  44949. /**
  44950. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44951. */
  44952. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  44953. /**
  44954. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44955. * They are also discarded below the alpha cutoff threshold to improve performances.
  44956. */
  44957. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  44958. __decorate([
  44959. BABYLON.serialize(),
  44960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44961. ], PBRMaterial.prototype, "directIntensity", void 0);
  44962. __decorate([
  44963. BABYLON.serialize(),
  44964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44965. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  44966. __decorate([
  44967. BABYLON.serialize(),
  44968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44969. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  44970. __decorate([
  44971. BABYLON.serialize(),
  44972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44973. ], PBRMaterial.prototype, "specularIntensity", void 0);
  44974. __decorate([
  44975. BABYLON.serialize(),
  44976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44977. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  44978. __decorate([
  44979. BABYLON.serializeAsTexture(),
  44980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44981. ], PBRMaterial.prototype, "albedoTexture", void 0);
  44982. __decorate([
  44983. BABYLON.serializeAsTexture(),
  44984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44985. ], PBRMaterial.prototype, "ambientTexture", void 0);
  44986. __decorate([
  44987. BABYLON.serialize(),
  44988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44989. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  44990. __decorate([
  44991. BABYLON.serializeAsTexture(),
  44992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44993. ], PBRMaterial.prototype, "opacityTexture", void 0);
  44994. __decorate([
  44995. BABYLON.serializeAsTexture(),
  44996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44997. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  44998. __decorate([
  44999. BABYLON.serializeAsTexture(),
  45000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45001. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45002. __decorate([
  45003. BABYLON.serializeAsTexture(),
  45004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45005. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45006. __decorate([
  45007. BABYLON.serializeAsTexture(),
  45008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45009. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45010. __decorate([
  45011. BABYLON.serialize(),
  45012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45013. ], PBRMaterial.prototype, "metallic", void 0);
  45014. __decorate([
  45015. BABYLON.serialize(),
  45016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45017. ], PBRMaterial.prototype, "roughness", void 0);
  45018. __decorate([
  45019. BABYLON.serializeAsTexture(),
  45020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45021. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45022. __decorate([
  45023. BABYLON.serializeAsTexture(),
  45024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45025. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45026. __decorate([
  45027. BABYLON.serializeAsTexture(),
  45028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45029. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45030. __decorate([
  45031. BABYLON.serializeAsTexture(),
  45032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45033. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45034. __decorate([
  45035. BABYLON.serializeAsColor3("ambient"),
  45036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45037. ], PBRMaterial.prototype, "ambientColor", void 0);
  45038. __decorate([
  45039. BABYLON.serializeAsColor3("albedo"),
  45040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45041. ], PBRMaterial.prototype, "albedoColor", void 0);
  45042. __decorate([
  45043. BABYLON.serializeAsColor3("reflectivity"),
  45044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45045. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45046. __decorate([
  45047. BABYLON.serializeAsColor3("reflection"),
  45048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45049. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45050. __decorate([
  45051. BABYLON.serializeAsColor3("emissive"),
  45052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45053. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45054. __decorate([
  45055. BABYLON.serialize(),
  45056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45057. ], PBRMaterial.prototype, "microSurface", void 0);
  45058. __decorate([
  45059. BABYLON.serialize(),
  45060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45061. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45062. __decorate([
  45063. BABYLON.serialize(),
  45064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45065. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45066. __decorate([
  45067. BABYLON.serialize(),
  45068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45069. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45070. __decorate([
  45071. BABYLON.serialize(),
  45072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45073. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45074. __decorate([
  45075. BABYLON.serialize(),
  45076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45077. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45078. __decorate([
  45079. BABYLON.serialize(),
  45080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45081. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45082. __decorate([
  45083. BABYLON.serialize(),
  45084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45085. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45086. __decorate([
  45087. BABYLON.serialize(),
  45088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45089. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45090. __decorate([
  45091. BABYLON.serialize(),
  45092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45093. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45094. __decorate([
  45095. BABYLON.serialize(),
  45096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45097. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45098. __decorate([
  45099. BABYLON.serialize(),
  45100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45101. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45102. __decorate([
  45103. BABYLON.serialize(),
  45104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45105. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45106. __decorate([
  45107. BABYLON.serialize(),
  45108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45109. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45110. __decorate([
  45111. BABYLON.serialize(),
  45112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45113. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45114. __decorate([
  45115. BABYLON.serialize(),
  45116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45117. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45118. __decorate([
  45119. BABYLON.serialize(),
  45120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45121. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45122. __decorate([
  45123. BABYLON.serialize(),
  45124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45125. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45126. __decorate([
  45127. BABYLON.serialize(),
  45128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45129. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45130. __decorate([
  45131. BABYLON.serialize(),
  45132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45133. ], PBRMaterial.prototype, "useParallax", void 0);
  45134. __decorate([
  45135. BABYLON.serialize(),
  45136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45137. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45138. __decorate([
  45139. BABYLON.serialize(),
  45140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45141. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45142. __decorate([
  45143. BABYLON.serialize(),
  45144. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45145. ], PBRMaterial.prototype, "disableLighting", void 0);
  45146. __decorate([
  45147. BABYLON.serialize(),
  45148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45149. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45150. __decorate([
  45151. BABYLON.serialize(),
  45152. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45153. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45154. __decorate([
  45155. BABYLON.serialize(),
  45156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45157. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45158. __decorate([
  45159. BABYLON.serialize(),
  45160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45161. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45162. __decorate([
  45163. BABYLON.serialize(),
  45164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45165. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45166. __decorate([
  45167. BABYLON.serialize(),
  45168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45169. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45170. __decorate([
  45171. BABYLON.serialize(),
  45172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45173. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45174. __decorate([
  45175. BABYLON.serializeAsTexture(),
  45176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45177. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45178. __decorate([
  45179. BABYLON.serialize(),
  45180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45181. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45182. __decorate([
  45183. BABYLON.serialize(),
  45184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45185. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45186. __decorate([
  45187. BABYLON.serialize(),
  45188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45189. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45190. __decorate([
  45191. BABYLON.serialize(),
  45192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45193. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45194. __decorate([
  45195. BABYLON.serialize(),
  45196. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45197. ], PBRMaterial.prototype, "unlit", void 0);
  45198. return PBRMaterial;
  45199. }(BABYLON.PBRBaseMaterial));
  45200. BABYLON.PBRMaterial = PBRMaterial;
  45201. })(BABYLON || (BABYLON = {}));
  45202. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45203. var BABYLON;
  45204. (function (BABYLON) {
  45205. /**
  45206. * The PBR material of BJS following the metal roughness convention.
  45207. *
  45208. * This fits to the PBR convention in the GLTF definition:
  45209. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45210. */
  45211. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45212. __extends(PBRMetallicRoughnessMaterial, _super);
  45213. /**
  45214. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45215. *
  45216. * @param name The material name
  45217. * @param scene The scene the material will be use in.
  45218. */
  45219. function PBRMetallicRoughnessMaterial(name, scene) {
  45220. var _this = _super.call(this, name, scene) || this;
  45221. _this._useRoughnessFromMetallicTextureAlpha = false;
  45222. _this._useRoughnessFromMetallicTextureGreen = true;
  45223. _this._useMetallnessFromMetallicTextureBlue = true;
  45224. _this.metallic = 1.0;
  45225. _this.roughness = 1.0;
  45226. return _this;
  45227. }
  45228. /**
  45229. * Return the currrent class name of the material.
  45230. */
  45231. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45232. return "PBRMetallicRoughnessMaterial";
  45233. };
  45234. /**
  45235. * Return the active textures of the material.
  45236. */
  45237. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45238. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45239. if (this.baseTexture) {
  45240. activeTextures.push(this.baseTexture);
  45241. }
  45242. if (this.metallicRoughnessTexture) {
  45243. activeTextures.push(this.metallicRoughnessTexture);
  45244. }
  45245. return activeTextures;
  45246. };
  45247. /**
  45248. * Checks to see if a texture is used in the material.
  45249. * @param texture - Base texture to use.
  45250. * @returns - Boolean specifying if a texture is used in the material.
  45251. */
  45252. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45253. if (_super.prototype.hasTexture.call(this, texture)) {
  45254. return true;
  45255. }
  45256. if (this.baseTexture === texture) {
  45257. return true;
  45258. }
  45259. if (this.metallicRoughnessTexture === texture) {
  45260. return true;
  45261. }
  45262. return false;
  45263. };
  45264. /**
  45265. * Makes a duplicate of the current material.
  45266. * @param name - name to use for the new material.
  45267. */
  45268. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45269. var _this = this;
  45270. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45271. clone.id = name;
  45272. clone.name = name;
  45273. return clone;
  45274. };
  45275. /**
  45276. * Serialize the material to a parsable JSON object.
  45277. */
  45278. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45279. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45280. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45281. return serializationObject;
  45282. };
  45283. /**
  45284. * Parses a JSON object correponding to the serialize function.
  45285. */
  45286. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45287. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45288. };
  45289. __decorate([
  45290. BABYLON.serializeAsColor3(),
  45291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45292. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45293. __decorate([
  45294. BABYLON.serializeAsTexture(),
  45295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45296. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45297. __decorate([
  45298. BABYLON.serialize(),
  45299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45300. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45301. __decorate([
  45302. BABYLON.serialize(),
  45303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45304. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45305. __decorate([
  45306. BABYLON.serializeAsTexture(),
  45307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45308. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45309. return PBRMetallicRoughnessMaterial;
  45310. }(BABYLON.PBRBaseSimpleMaterial));
  45311. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45312. })(BABYLON || (BABYLON = {}));
  45313. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45314. var BABYLON;
  45315. (function (BABYLON) {
  45316. /**
  45317. * The PBR material of BJS following the specular glossiness convention.
  45318. *
  45319. * This fits to the PBR convention in the GLTF definition:
  45320. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45321. */
  45322. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45323. __extends(PBRSpecularGlossinessMaterial, _super);
  45324. /**
  45325. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45326. *
  45327. * @param name The material name
  45328. * @param scene The scene the material will be use in.
  45329. */
  45330. function PBRSpecularGlossinessMaterial(name, scene) {
  45331. var _this = _super.call(this, name, scene) || this;
  45332. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45333. return _this;
  45334. }
  45335. /**
  45336. * Return the currrent class name of the material.
  45337. */
  45338. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45339. return "PBRSpecularGlossinessMaterial";
  45340. };
  45341. /**
  45342. * Return the active textures of the material.
  45343. */
  45344. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45345. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45346. if (this.diffuseTexture) {
  45347. activeTextures.push(this.diffuseTexture);
  45348. }
  45349. if (this.specularGlossinessTexture) {
  45350. activeTextures.push(this.specularGlossinessTexture);
  45351. }
  45352. return activeTextures;
  45353. };
  45354. /**
  45355. * Checks to see if a texture is used in the material.
  45356. * @param texture - Base texture to use.
  45357. * @returns - Boolean specifying if a texture is used in the material.
  45358. */
  45359. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45360. if (_super.prototype.hasTexture.call(this, texture)) {
  45361. return true;
  45362. }
  45363. if (this.diffuseTexture === texture) {
  45364. return true;
  45365. }
  45366. if (this.specularGlossinessTexture === texture) {
  45367. return true;
  45368. }
  45369. return false;
  45370. };
  45371. /**
  45372. * Makes a duplicate of the current material.
  45373. * @param name - name to use for the new material.
  45374. */
  45375. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45376. var _this = this;
  45377. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45378. clone.id = name;
  45379. clone.name = name;
  45380. return clone;
  45381. };
  45382. /**
  45383. * Serialize the material to a parsable JSON object.
  45384. */
  45385. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45386. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45387. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45388. return serializationObject;
  45389. };
  45390. /**
  45391. * Parses a JSON object correponding to the serialize function.
  45392. */
  45393. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45394. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45395. };
  45396. __decorate([
  45397. BABYLON.serializeAsColor3("diffuse"),
  45398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45399. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45400. __decorate([
  45401. BABYLON.serializeAsTexture(),
  45402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45403. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45404. __decorate([
  45405. BABYLON.serializeAsColor3("specular"),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45407. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45408. __decorate([
  45409. BABYLON.serialize(),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45411. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45412. __decorate([
  45413. BABYLON.serializeAsTexture(),
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45415. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45416. return PBRSpecularGlossinessMaterial;
  45417. }(BABYLON.PBRBaseSimpleMaterial));
  45418. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45419. })(BABYLON || (BABYLON = {}));
  45420. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45421. var BABYLON;
  45422. (function (BABYLON) {
  45423. BABYLON.CameraInputTypes = {};
  45424. var CameraInputsManager = /** @class */ (function () {
  45425. function CameraInputsManager(camera) {
  45426. this.attached = {};
  45427. this.camera = camera;
  45428. this.checkInputs = function () { };
  45429. }
  45430. /**
  45431. * Add an input method to a camera
  45432. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45433. * @param input camera input method
  45434. */
  45435. CameraInputsManager.prototype.add = function (input) {
  45436. var type = input.getSimpleName();
  45437. if (this.attached[type]) {
  45438. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45439. return;
  45440. }
  45441. this.attached[type] = input;
  45442. input.camera = this.camera;
  45443. //for checkInputs, we are dynamically creating a function
  45444. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45445. if (input.checkInputs) {
  45446. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45447. }
  45448. if (this.attachedElement) {
  45449. input.attachControl(this.attachedElement);
  45450. }
  45451. };
  45452. /**
  45453. * Remove a specific input method from a camera
  45454. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45455. * @param inputToRemove camera input method
  45456. */
  45457. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45458. for (var cam in this.attached) {
  45459. var input = this.attached[cam];
  45460. if (input === inputToRemove) {
  45461. input.detachControl(this.attachedElement);
  45462. input.camera = null;
  45463. delete this.attached[cam];
  45464. this.rebuildInputCheck();
  45465. }
  45466. }
  45467. };
  45468. CameraInputsManager.prototype.removeByType = function (inputType) {
  45469. for (var cam in this.attached) {
  45470. var input = this.attached[cam];
  45471. if (input.getClassName() === inputType) {
  45472. input.detachControl(this.attachedElement);
  45473. input.camera = null;
  45474. delete this.attached[cam];
  45475. this.rebuildInputCheck();
  45476. }
  45477. }
  45478. };
  45479. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45480. var current = this.checkInputs;
  45481. return function () {
  45482. current();
  45483. fn();
  45484. };
  45485. };
  45486. CameraInputsManager.prototype.attachInput = function (input) {
  45487. if (this.attachedElement) {
  45488. input.attachControl(this.attachedElement, this.noPreventDefault);
  45489. }
  45490. };
  45491. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45492. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45493. if (this.attachedElement) {
  45494. return;
  45495. }
  45496. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45497. this.attachedElement = element;
  45498. this.noPreventDefault = noPreventDefault;
  45499. for (var cam in this.attached) {
  45500. this.attached[cam].attachControl(element, noPreventDefault);
  45501. }
  45502. };
  45503. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45504. if (disconnect === void 0) { disconnect = false; }
  45505. if (this.attachedElement !== element) {
  45506. return;
  45507. }
  45508. for (var cam in this.attached) {
  45509. this.attached[cam].detachControl(element);
  45510. if (disconnect) {
  45511. this.attached[cam].camera = null;
  45512. }
  45513. }
  45514. this.attachedElement = null;
  45515. };
  45516. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45517. this.checkInputs = function () { };
  45518. for (var cam in this.attached) {
  45519. var input = this.attached[cam];
  45520. if (input.checkInputs) {
  45521. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45522. }
  45523. }
  45524. };
  45525. /**
  45526. * Remove all attached input methods from a camera
  45527. */
  45528. CameraInputsManager.prototype.clear = function () {
  45529. if (this.attachedElement) {
  45530. this.detachElement(this.attachedElement, true);
  45531. }
  45532. this.attached = {};
  45533. this.attachedElement = null;
  45534. this.checkInputs = function () { };
  45535. };
  45536. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45537. var inputs = {};
  45538. for (var cam in this.attached) {
  45539. var input = this.attached[cam];
  45540. var res = BABYLON.SerializationHelper.Serialize(input);
  45541. inputs[input.getClassName()] = res;
  45542. }
  45543. serializedCamera.inputsmgr = inputs;
  45544. };
  45545. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45546. var parsedInputs = parsedCamera.inputsmgr;
  45547. if (parsedInputs) {
  45548. this.clear();
  45549. for (var n in parsedInputs) {
  45550. var construct = BABYLON.CameraInputTypes[n];
  45551. if (construct) {
  45552. var parsedinput = parsedInputs[n];
  45553. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45554. this.add(input);
  45555. }
  45556. }
  45557. }
  45558. else {
  45559. //2016-03-08 this part is for managing backward compatibility
  45560. for (var n in this.attached) {
  45561. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45562. if (construct) {
  45563. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45564. this.remove(this.attached[n]);
  45565. this.add(input);
  45566. }
  45567. }
  45568. }
  45569. };
  45570. return CameraInputsManager;
  45571. }());
  45572. BABYLON.CameraInputsManager = CameraInputsManager;
  45573. })(BABYLON || (BABYLON = {}));
  45574. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45575. var BABYLON;
  45576. (function (BABYLON) {
  45577. var TargetCamera = /** @class */ (function (_super) {
  45578. __extends(TargetCamera, _super);
  45579. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45580. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45581. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45582. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45583. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45584. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45585. _this.speed = 2.0;
  45586. _this.noRotationConstraint = false;
  45587. _this.lockedTarget = null;
  45588. _this._currentTarget = BABYLON.Vector3.Zero();
  45589. _this._viewMatrix = BABYLON.Matrix.Zero();
  45590. _this._camMatrix = BABYLON.Matrix.Zero();
  45591. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45592. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45593. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45594. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45595. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45596. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45597. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45598. return _this;
  45599. }
  45600. TargetCamera.prototype.getFrontPosition = function (distance) {
  45601. this.getWorldMatrix();
  45602. var direction = this.getTarget().subtract(this.position);
  45603. direction.normalize();
  45604. direction.scaleInPlace(distance);
  45605. return this.globalPosition.add(direction);
  45606. };
  45607. TargetCamera.prototype._getLockedTargetPosition = function () {
  45608. if (!this.lockedTarget) {
  45609. return null;
  45610. }
  45611. if (this.lockedTarget.absolutePosition) {
  45612. this.lockedTarget.computeWorldMatrix();
  45613. }
  45614. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45615. };
  45616. TargetCamera.prototype.storeState = function () {
  45617. this._storedPosition = this.position.clone();
  45618. this._storedRotation = this.rotation.clone();
  45619. if (this.rotationQuaternion) {
  45620. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45621. }
  45622. return _super.prototype.storeState.call(this);
  45623. };
  45624. /**
  45625. * Restored camera state. You must call storeState() first
  45626. */
  45627. TargetCamera.prototype._restoreStateValues = function () {
  45628. if (!_super.prototype._restoreStateValues.call(this)) {
  45629. return false;
  45630. }
  45631. this.position = this._storedPosition.clone();
  45632. this.rotation = this._storedRotation.clone();
  45633. if (this.rotationQuaternion) {
  45634. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45635. }
  45636. this.cameraDirection.copyFromFloats(0, 0, 0);
  45637. this.cameraRotation.copyFromFloats(0, 0);
  45638. return true;
  45639. };
  45640. // Cache
  45641. TargetCamera.prototype._initCache = function () {
  45642. _super.prototype._initCache.call(this);
  45643. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45644. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45645. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45646. };
  45647. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45648. if (!ignoreParentClass) {
  45649. _super.prototype._updateCache.call(this);
  45650. }
  45651. var lockedTargetPosition = this._getLockedTargetPosition();
  45652. if (!lockedTargetPosition) {
  45653. this._cache.lockedTarget = null;
  45654. }
  45655. else {
  45656. if (!this._cache.lockedTarget) {
  45657. this._cache.lockedTarget = lockedTargetPosition.clone();
  45658. }
  45659. else {
  45660. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45661. }
  45662. }
  45663. this._cache.rotation.copyFrom(this.rotation);
  45664. if (this.rotationQuaternion)
  45665. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45666. };
  45667. // Synchronized
  45668. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45669. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45670. return false;
  45671. }
  45672. var lockedTargetPosition = this._getLockedTargetPosition();
  45673. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45674. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45675. };
  45676. // Methods
  45677. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45678. var engine = this.getEngine();
  45679. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45680. };
  45681. // Target
  45682. TargetCamera.prototype.setTarget = function (target) {
  45683. this.upVector.normalize();
  45684. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45685. this._camMatrix.invert();
  45686. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45687. var vDir = target.subtract(this.position);
  45688. if (vDir.x >= 0.0) {
  45689. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45690. }
  45691. else {
  45692. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45693. }
  45694. this.rotation.z = 0;
  45695. if (isNaN(this.rotation.x)) {
  45696. this.rotation.x = 0;
  45697. }
  45698. if (isNaN(this.rotation.y)) {
  45699. this.rotation.y = 0;
  45700. }
  45701. if (isNaN(this.rotation.z)) {
  45702. this.rotation.z = 0;
  45703. }
  45704. if (this.rotationQuaternion) {
  45705. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45706. }
  45707. };
  45708. /**
  45709. * Return the current target position of the camera. This value is expressed in local space.
  45710. */
  45711. TargetCamera.prototype.getTarget = function () {
  45712. return this._currentTarget;
  45713. };
  45714. TargetCamera.prototype._decideIfNeedsToMove = function () {
  45715. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45716. };
  45717. TargetCamera.prototype._updatePosition = function () {
  45718. if (this.parent) {
  45719. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  45720. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  45721. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  45722. return;
  45723. }
  45724. this.position.addInPlace(this.cameraDirection);
  45725. };
  45726. TargetCamera.prototype._checkInputs = function () {
  45727. var needToMove = this._decideIfNeedsToMove();
  45728. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  45729. // Move
  45730. if (needToMove) {
  45731. this._updatePosition();
  45732. }
  45733. // Rotate
  45734. if (needToRotate) {
  45735. this.rotation.x += this.cameraRotation.x;
  45736. this.rotation.y += this.cameraRotation.y;
  45737. //rotate, if quaternion is set and rotation was used
  45738. if (this.rotationQuaternion) {
  45739. var len = this.rotation.lengthSquared();
  45740. if (len) {
  45741. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45742. }
  45743. }
  45744. if (!this.noRotationConstraint) {
  45745. var limit = (Math.PI / 2) * 0.95;
  45746. if (this.rotation.x > limit)
  45747. this.rotation.x = limit;
  45748. if (this.rotation.x < -limit)
  45749. this.rotation.x = -limit;
  45750. }
  45751. }
  45752. // Inertia
  45753. if (needToMove) {
  45754. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  45755. this.cameraDirection.x = 0;
  45756. }
  45757. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  45758. this.cameraDirection.y = 0;
  45759. }
  45760. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  45761. this.cameraDirection.z = 0;
  45762. }
  45763. this.cameraDirection.scaleInPlace(this.inertia);
  45764. }
  45765. if (needToRotate) {
  45766. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  45767. this.cameraRotation.x = 0;
  45768. }
  45769. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  45770. this.cameraRotation.y = 0;
  45771. }
  45772. this.cameraRotation.scaleInPlace(this.inertia);
  45773. }
  45774. _super.prototype._checkInputs.call(this);
  45775. };
  45776. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  45777. if (this.rotationQuaternion) {
  45778. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  45779. }
  45780. else {
  45781. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  45782. }
  45783. //update the up vector!
  45784. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  45785. };
  45786. TargetCamera.prototype._getViewMatrix = function () {
  45787. if (this.lockedTarget) {
  45788. this.setTarget(this._getLockedTargetPosition());
  45789. }
  45790. // Compute
  45791. this._updateCameraRotationMatrix();
  45792. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  45793. // Computing target and final matrix
  45794. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  45795. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  45796. return this._viewMatrix;
  45797. };
  45798. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  45799. if (this.parent) {
  45800. var parentWorldMatrix = this.parent.getWorldMatrix();
  45801. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  45802. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  45803. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  45804. this._markSyncedWithParent();
  45805. }
  45806. else {
  45807. this._globalPosition.copyFrom(this.position);
  45808. this._globalCurrentTarget.copyFrom(target);
  45809. this._globalCurrentUpVector.copyFrom(up);
  45810. }
  45811. if (this.getScene().useRightHandedSystem) {
  45812. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45813. }
  45814. else {
  45815. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  45816. }
  45817. };
  45818. /**
  45819. * @override
  45820. * Override Camera.createRigCamera
  45821. */
  45822. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45823. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  45824. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  45825. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  45826. if (!this.rotationQuaternion) {
  45827. this.rotationQuaternion = new BABYLON.Quaternion();
  45828. }
  45829. rigCamera._cameraRigParams = {};
  45830. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  45831. }
  45832. return rigCamera;
  45833. }
  45834. return null;
  45835. };
  45836. /**
  45837. * @override
  45838. * Override Camera._updateRigCameras
  45839. */
  45840. TargetCamera.prototype._updateRigCameras = function () {
  45841. var camLeft = this._rigCameras[0];
  45842. var camRight = this._rigCameras[1];
  45843. switch (this.cameraRigMode) {
  45844. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45845. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45846. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45848. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  45849. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  45850. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  45851. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  45852. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  45853. camLeft.setTarget(this.getTarget());
  45854. camRight.setTarget(this.getTarget());
  45855. break;
  45856. case BABYLON.Camera.RIG_MODE_VR:
  45857. if (camLeft.rotationQuaternion) {
  45858. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45859. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45860. }
  45861. else {
  45862. camLeft.rotation.copyFrom(this.rotation);
  45863. camRight.rotation.copyFrom(this.rotation);
  45864. }
  45865. camLeft.position.copyFrom(this.position);
  45866. camRight.position.copyFrom(this.position);
  45867. break;
  45868. }
  45869. _super.prototype._updateRigCameras.call(this);
  45870. };
  45871. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  45872. if (!this._rigCamTransformMatrix) {
  45873. this._rigCamTransformMatrix = new BABYLON.Matrix();
  45874. }
  45875. var target = this.getTarget();
  45876. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  45877. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  45878. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  45879. };
  45880. TargetCamera.prototype.getClassName = function () {
  45881. return "TargetCamera";
  45882. };
  45883. __decorate([
  45884. BABYLON.serializeAsVector3()
  45885. ], TargetCamera.prototype, "rotation", void 0);
  45886. __decorate([
  45887. BABYLON.serialize()
  45888. ], TargetCamera.prototype, "speed", void 0);
  45889. __decorate([
  45890. BABYLON.serializeAsMeshReference("lockedTargetId")
  45891. ], TargetCamera.prototype, "lockedTarget", void 0);
  45892. return TargetCamera;
  45893. }(BABYLON.Camera));
  45894. BABYLON.TargetCamera = TargetCamera;
  45895. })(BABYLON || (BABYLON = {}));
  45896. //# sourceMappingURL=babylon.targetCamera.js.map
  45897. var BABYLON;
  45898. (function (BABYLON) {
  45899. var FreeCameraMouseInput = /** @class */ (function () {
  45900. function FreeCameraMouseInput(touchEnabled) {
  45901. if (touchEnabled === void 0) { touchEnabled = true; }
  45902. this.touchEnabled = touchEnabled;
  45903. this.buttons = [0, 1, 2];
  45904. this.angularSensibility = 2000.0;
  45905. this.previousPosition = null;
  45906. }
  45907. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  45908. var _this = this;
  45909. var engine = this.camera.getEngine();
  45910. if (!this._pointerInput) {
  45911. this._pointerInput = function (p, s) {
  45912. var evt = p.event;
  45913. if (engine.isInVRExclusivePointerMode) {
  45914. return;
  45915. }
  45916. if (!_this.touchEnabled && evt.pointerType === "touch") {
  45917. return;
  45918. }
  45919. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45920. return;
  45921. }
  45922. var srcElement = (evt.srcElement || evt.target);
  45923. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45924. try {
  45925. srcElement.setPointerCapture(evt.pointerId);
  45926. }
  45927. catch (e) {
  45928. //Nothing to do with the error. Execution will continue.
  45929. }
  45930. _this.previousPosition = {
  45931. x: evt.clientX,
  45932. y: evt.clientY
  45933. };
  45934. if (!noPreventDefault) {
  45935. evt.preventDefault();
  45936. element.focus();
  45937. }
  45938. }
  45939. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45940. try {
  45941. srcElement.releasePointerCapture(evt.pointerId);
  45942. }
  45943. catch (e) {
  45944. //Nothing to do with the error.
  45945. }
  45946. _this.previousPosition = null;
  45947. if (!noPreventDefault) {
  45948. evt.preventDefault();
  45949. }
  45950. }
  45951. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45952. if (!_this.previousPosition || engine.isPointerLock) {
  45953. return;
  45954. }
  45955. var offsetX = evt.clientX - _this.previousPosition.x;
  45956. if (_this.camera.getScene().useRightHandedSystem)
  45957. offsetX *= -1;
  45958. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45959. offsetX *= -1;
  45960. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45961. var offsetY = evt.clientY - _this.previousPosition.y;
  45962. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45963. _this.previousPosition = {
  45964. x: evt.clientX,
  45965. y: evt.clientY
  45966. };
  45967. if (!noPreventDefault) {
  45968. evt.preventDefault();
  45969. }
  45970. }
  45971. };
  45972. }
  45973. this._onMouseMove = function (evt) {
  45974. if (!engine.isPointerLock) {
  45975. return;
  45976. }
  45977. if (engine.isInVRExclusivePointerMode) {
  45978. return;
  45979. }
  45980. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  45981. if (_this.camera.getScene().useRightHandedSystem)
  45982. offsetX *= -1;
  45983. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  45984. offsetX *= -1;
  45985. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  45986. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  45987. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  45988. _this.previousPosition = null;
  45989. if (!noPreventDefault) {
  45990. evt.preventDefault();
  45991. }
  45992. };
  45993. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  45994. element.addEventListener("mousemove", this._onMouseMove, false);
  45995. };
  45996. FreeCameraMouseInput.prototype.detachControl = function (element) {
  45997. if (this._observer && element) {
  45998. this.camera.getScene().onPointerObservable.remove(this._observer);
  45999. if (this._onMouseMove) {
  46000. element.removeEventListener("mousemove", this._onMouseMove);
  46001. }
  46002. this._observer = null;
  46003. this._onMouseMove = null;
  46004. this.previousPosition = null;
  46005. }
  46006. };
  46007. FreeCameraMouseInput.prototype.getClassName = function () {
  46008. return "FreeCameraMouseInput";
  46009. };
  46010. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46011. return "mouse";
  46012. };
  46013. __decorate([
  46014. BABYLON.serialize()
  46015. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46016. __decorate([
  46017. BABYLON.serialize()
  46018. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46019. return FreeCameraMouseInput;
  46020. }());
  46021. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46022. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46023. })(BABYLON || (BABYLON = {}));
  46024. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46025. var BABYLON;
  46026. (function (BABYLON) {
  46027. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46028. function FreeCameraKeyboardMoveInput() {
  46029. this._keys = new Array();
  46030. this.keysUp = [38];
  46031. this.keysDown = [40];
  46032. this.keysLeft = [37];
  46033. this.keysRight = [39];
  46034. }
  46035. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46036. var _this = this;
  46037. if (this._onCanvasBlurObserver) {
  46038. return;
  46039. }
  46040. this._scene = this.camera.getScene();
  46041. this._engine = this._scene.getEngine();
  46042. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46043. _this._keys = [];
  46044. });
  46045. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46046. var evt = info.event;
  46047. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46048. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46049. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46050. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46051. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46052. var index = _this._keys.indexOf(evt.keyCode);
  46053. if (index === -1) {
  46054. _this._keys.push(evt.keyCode);
  46055. }
  46056. if (!noPreventDefault) {
  46057. evt.preventDefault();
  46058. }
  46059. }
  46060. }
  46061. else {
  46062. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46063. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46064. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46065. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46066. var index = _this._keys.indexOf(evt.keyCode);
  46067. if (index >= 0) {
  46068. _this._keys.splice(index, 1);
  46069. }
  46070. if (!noPreventDefault) {
  46071. evt.preventDefault();
  46072. }
  46073. }
  46074. }
  46075. });
  46076. };
  46077. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46078. if (this._scene) {
  46079. if (this._onKeyboardObserver) {
  46080. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46081. }
  46082. if (this._onCanvasBlurObserver) {
  46083. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46084. }
  46085. this._onKeyboardObserver = null;
  46086. this._onCanvasBlurObserver = null;
  46087. }
  46088. this._keys = [];
  46089. };
  46090. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46091. if (this._onKeyboardObserver) {
  46092. var camera = this.camera;
  46093. // Keyboard
  46094. for (var index = 0; index < this._keys.length; index++) {
  46095. var keyCode = this._keys[index];
  46096. var speed = camera._computeLocalCameraSpeed();
  46097. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46098. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46099. }
  46100. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46101. camera._localDirection.copyFromFloats(0, 0, speed);
  46102. }
  46103. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46104. camera._localDirection.copyFromFloats(speed, 0, 0);
  46105. }
  46106. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46107. camera._localDirection.copyFromFloats(0, 0, -speed);
  46108. }
  46109. if (camera.getScene().useRightHandedSystem) {
  46110. camera._localDirection.z *= -1;
  46111. }
  46112. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46113. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46114. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46115. }
  46116. }
  46117. };
  46118. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46119. return "FreeCameraKeyboardMoveInput";
  46120. };
  46121. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46122. this._keys = [];
  46123. };
  46124. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46125. return "keyboard";
  46126. };
  46127. __decorate([
  46128. BABYLON.serialize()
  46129. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46130. __decorate([
  46131. BABYLON.serialize()
  46132. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46133. __decorate([
  46134. BABYLON.serialize()
  46135. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46136. __decorate([
  46137. BABYLON.serialize()
  46138. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46139. return FreeCameraKeyboardMoveInput;
  46140. }());
  46141. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46142. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46143. })(BABYLON || (BABYLON = {}));
  46144. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46145. var BABYLON;
  46146. (function (BABYLON) {
  46147. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46148. __extends(FreeCameraInputsManager, _super);
  46149. function FreeCameraInputsManager(camera) {
  46150. return _super.call(this, camera) || this;
  46151. }
  46152. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46153. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46154. return this;
  46155. };
  46156. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46157. if (touchEnabled === void 0) { touchEnabled = true; }
  46158. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46159. return this;
  46160. };
  46161. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46162. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46163. return this;
  46164. };
  46165. FreeCameraInputsManager.prototype.addTouch = function () {
  46166. this.add(new BABYLON.FreeCameraTouchInput());
  46167. return this;
  46168. };
  46169. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46170. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46171. return this;
  46172. };
  46173. return FreeCameraInputsManager;
  46174. }(BABYLON.CameraInputsManager));
  46175. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46176. })(BABYLON || (BABYLON = {}));
  46177. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46178. var BABYLON;
  46179. (function (BABYLON) {
  46180. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46181. // Forcing to use the Universal camera
  46182. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46183. });
  46184. var FreeCamera = /** @class */ (function (_super) {
  46185. __extends(FreeCamera, _super);
  46186. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46187. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46188. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46189. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46190. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46191. _this.checkCollisions = false;
  46192. _this.applyGravity = false;
  46193. _this._needMoveForGravity = false;
  46194. _this._oldPosition = BABYLON.Vector3.Zero();
  46195. _this._diffPosition = BABYLON.Vector3.Zero();
  46196. _this._newPosition = BABYLON.Vector3.Zero();
  46197. // Collisions
  46198. _this._collisionMask = -1;
  46199. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46200. if (collidedMesh === void 0) { collidedMesh = null; }
  46201. //TODO move this to the collision coordinator!
  46202. if (_this.getScene().workerCollisions)
  46203. newPosition.multiplyInPlace(_this._collider._radius);
  46204. var updatePosition = function (newPos) {
  46205. _this._newPosition.copyFrom(newPos);
  46206. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46207. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46208. _this.position.addInPlace(_this._diffPosition);
  46209. if (_this.onCollide && collidedMesh) {
  46210. _this.onCollide(collidedMesh);
  46211. }
  46212. }
  46213. };
  46214. updatePosition(newPosition);
  46215. };
  46216. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46217. _this.inputs.addKeyboard().addMouse();
  46218. return _this;
  46219. }
  46220. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46221. //-- begin properties for backward compatibility for inputs
  46222. /**
  46223. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46224. * Higher values reduce sensitivity.
  46225. */
  46226. get: function () {
  46227. var mouse = this.inputs.attached["mouse"];
  46228. if (mouse)
  46229. return mouse.angularSensibility;
  46230. return 0;
  46231. },
  46232. /**
  46233. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46234. * Higher values reduce sensitivity.
  46235. */
  46236. set: function (value) {
  46237. var mouse = this.inputs.attached["mouse"];
  46238. if (mouse)
  46239. mouse.angularSensibility = value;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46245. get: function () {
  46246. var keyboard = this.inputs.attached["keyboard"];
  46247. if (keyboard)
  46248. return keyboard.keysUp;
  46249. return [];
  46250. },
  46251. set: function (value) {
  46252. var keyboard = this.inputs.attached["keyboard"];
  46253. if (keyboard)
  46254. keyboard.keysUp = value;
  46255. },
  46256. enumerable: true,
  46257. configurable: true
  46258. });
  46259. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46260. get: function () {
  46261. var keyboard = this.inputs.attached["keyboard"];
  46262. if (keyboard)
  46263. return keyboard.keysDown;
  46264. return [];
  46265. },
  46266. set: function (value) {
  46267. var keyboard = this.inputs.attached["keyboard"];
  46268. if (keyboard)
  46269. keyboard.keysDown = value;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46275. get: function () {
  46276. var keyboard = this.inputs.attached["keyboard"];
  46277. if (keyboard)
  46278. return keyboard.keysLeft;
  46279. return [];
  46280. },
  46281. set: function (value) {
  46282. var keyboard = this.inputs.attached["keyboard"];
  46283. if (keyboard)
  46284. keyboard.keysLeft = value;
  46285. },
  46286. enumerable: true,
  46287. configurable: true
  46288. });
  46289. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46290. get: function () {
  46291. var keyboard = this.inputs.attached["keyboard"];
  46292. if (keyboard)
  46293. return keyboard.keysRight;
  46294. return [];
  46295. },
  46296. set: function (value) {
  46297. var keyboard = this.inputs.attached["keyboard"];
  46298. if (keyboard)
  46299. keyboard.keysRight = value;
  46300. },
  46301. enumerable: true,
  46302. configurable: true
  46303. });
  46304. // Controls
  46305. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46306. this.inputs.attachElement(element, noPreventDefault);
  46307. };
  46308. FreeCamera.prototype.detachControl = function (element) {
  46309. this.inputs.detachElement(element);
  46310. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46311. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46312. };
  46313. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46314. get: function () {
  46315. return this._collisionMask;
  46316. },
  46317. set: function (mask) {
  46318. this._collisionMask = !isNaN(mask) ? mask : -1;
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46324. var globalPosition;
  46325. if (this.parent) {
  46326. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46327. }
  46328. else {
  46329. globalPosition = this.position;
  46330. }
  46331. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46332. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46333. if (!this._collider) {
  46334. this._collider = new BABYLON.Collider();
  46335. }
  46336. this._collider._radius = this.ellipsoid;
  46337. this._collider.collisionMask = this._collisionMask;
  46338. //no need for clone, as long as gravity is not on.
  46339. var actualDisplacement = displacement;
  46340. //add gravity to the direction to prevent the dual-collision checking
  46341. if (this.applyGravity) {
  46342. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46343. actualDisplacement = displacement.add(this.getScene().gravity);
  46344. }
  46345. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46346. };
  46347. FreeCamera.prototype._checkInputs = function () {
  46348. if (!this._localDirection) {
  46349. this._localDirection = BABYLON.Vector3.Zero();
  46350. this._transformedDirection = BABYLON.Vector3.Zero();
  46351. }
  46352. this.inputs.checkInputs();
  46353. _super.prototype._checkInputs.call(this);
  46354. };
  46355. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46356. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46357. };
  46358. FreeCamera.prototype._updatePosition = function () {
  46359. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46360. this._collideWithWorld(this.cameraDirection);
  46361. }
  46362. else {
  46363. _super.prototype._updatePosition.call(this);
  46364. }
  46365. };
  46366. FreeCamera.prototype.dispose = function () {
  46367. this.inputs.clear();
  46368. _super.prototype.dispose.call(this);
  46369. };
  46370. FreeCamera.prototype.getClassName = function () {
  46371. return "FreeCamera";
  46372. };
  46373. __decorate([
  46374. BABYLON.serializeAsVector3()
  46375. ], FreeCamera.prototype, "ellipsoid", void 0);
  46376. __decorate([
  46377. BABYLON.serializeAsVector3()
  46378. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46379. __decorate([
  46380. BABYLON.serialize()
  46381. ], FreeCamera.prototype, "checkCollisions", void 0);
  46382. __decorate([
  46383. BABYLON.serialize()
  46384. ], FreeCamera.prototype, "applyGravity", void 0);
  46385. return FreeCamera;
  46386. }(BABYLON.TargetCamera));
  46387. BABYLON.FreeCamera = FreeCamera;
  46388. })(BABYLON || (BABYLON = {}));
  46389. //# sourceMappingURL=babylon.freeCamera.js.map
  46390. var BABYLON;
  46391. (function (BABYLON) {
  46392. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46393. function ArcRotateCameraKeyboardMoveInput() {
  46394. this._keys = new Array();
  46395. this.keysUp = [38];
  46396. this.keysDown = [40];
  46397. this.keysLeft = [37];
  46398. this.keysRight = [39];
  46399. this.keysReset = [220];
  46400. this.panningSensibility = 50.0;
  46401. this.zoomingSensibility = 25.0;
  46402. this.useAltToZoom = true;
  46403. }
  46404. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46405. var _this = this;
  46406. if (this._onCanvasBlurObserver) {
  46407. return;
  46408. }
  46409. this._scene = this.camera.getScene();
  46410. this._engine = this._scene.getEngine();
  46411. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46412. _this._keys = [];
  46413. });
  46414. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46415. var evt = info.event;
  46416. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46417. _this._ctrlPressed = evt.ctrlKey;
  46418. _this._altPressed = evt.altKey;
  46419. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46420. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46421. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46422. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46423. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46424. var index = _this._keys.indexOf(evt.keyCode);
  46425. if (index === -1) {
  46426. _this._keys.push(evt.keyCode);
  46427. }
  46428. if (evt.preventDefault) {
  46429. if (!noPreventDefault) {
  46430. evt.preventDefault();
  46431. }
  46432. }
  46433. }
  46434. }
  46435. else {
  46436. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46437. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46438. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46439. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46440. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46441. var index = _this._keys.indexOf(evt.keyCode);
  46442. if (index >= 0) {
  46443. _this._keys.splice(index, 1);
  46444. }
  46445. if (evt.preventDefault) {
  46446. if (!noPreventDefault) {
  46447. evt.preventDefault();
  46448. }
  46449. }
  46450. }
  46451. }
  46452. });
  46453. };
  46454. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46455. if (this._scene) {
  46456. if (this._onKeyboardObserver) {
  46457. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46458. }
  46459. if (this._onCanvasBlurObserver) {
  46460. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46461. }
  46462. this._onKeyboardObserver = null;
  46463. this._onCanvasBlurObserver = null;
  46464. }
  46465. this._keys = [];
  46466. };
  46467. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46468. if (this._onKeyboardObserver) {
  46469. var camera = this.camera;
  46470. for (var index = 0; index < this._keys.length; index++) {
  46471. var keyCode = this._keys[index];
  46472. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46473. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46474. camera.inertialPanningX -= 1 / this.panningSensibility;
  46475. }
  46476. else {
  46477. camera.inertialAlphaOffset -= 0.01;
  46478. }
  46479. }
  46480. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46481. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46482. camera.inertialPanningY += 1 / this.panningSensibility;
  46483. }
  46484. else if (this._altPressed && this.useAltToZoom) {
  46485. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46486. }
  46487. else {
  46488. camera.inertialBetaOffset -= 0.01;
  46489. }
  46490. }
  46491. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46492. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46493. camera.inertialPanningX += 1 / this.panningSensibility;
  46494. }
  46495. else {
  46496. camera.inertialAlphaOffset += 0.01;
  46497. }
  46498. }
  46499. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46500. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46501. camera.inertialPanningY -= 1 / this.panningSensibility;
  46502. }
  46503. else if (this._altPressed && this.useAltToZoom) {
  46504. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46505. }
  46506. else {
  46507. camera.inertialBetaOffset += 0.01;
  46508. }
  46509. }
  46510. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46511. camera.restoreState();
  46512. }
  46513. }
  46514. }
  46515. };
  46516. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46517. return "ArcRotateCameraKeyboardMoveInput";
  46518. };
  46519. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46520. return "keyboard";
  46521. };
  46522. __decorate([
  46523. BABYLON.serialize()
  46524. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46525. __decorate([
  46526. BABYLON.serialize()
  46527. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46528. __decorate([
  46529. BABYLON.serialize()
  46530. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46531. __decorate([
  46532. BABYLON.serialize()
  46533. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46534. __decorate([
  46535. BABYLON.serialize()
  46536. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46537. __decorate([
  46538. BABYLON.serialize()
  46539. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46540. __decorate([
  46541. BABYLON.serialize()
  46542. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46543. __decorate([
  46544. BABYLON.serialize()
  46545. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46546. return ArcRotateCameraKeyboardMoveInput;
  46547. }());
  46548. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46549. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46550. })(BABYLON || (BABYLON = {}));
  46551. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46552. var BABYLON;
  46553. (function (BABYLON) {
  46554. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46555. function ArcRotateCameraMouseWheelInput() {
  46556. this.wheelPrecision = 3.0;
  46557. /**
  46558. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46559. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46560. */
  46561. this.wheelDeltaPercentage = 0;
  46562. }
  46563. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46564. var _this = this;
  46565. this._wheel = function (p, s) {
  46566. //sanity check - this should be a PointerWheel event.
  46567. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46568. return;
  46569. var event = p.event;
  46570. var delta = 0;
  46571. if (event.wheelDelta) {
  46572. if (_this.wheelDeltaPercentage) {
  46573. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46574. if (event.wheelDelta > 0) {
  46575. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46576. }
  46577. else {
  46578. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46579. }
  46580. }
  46581. else {
  46582. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46583. }
  46584. }
  46585. else if (event.detail) {
  46586. delta = -event.detail / _this.wheelPrecision;
  46587. }
  46588. if (delta)
  46589. _this.camera.inertialRadiusOffset += delta;
  46590. if (event.preventDefault) {
  46591. if (!noPreventDefault) {
  46592. event.preventDefault();
  46593. }
  46594. }
  46595. };
  46596. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46597. };
  46598. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46599. if (this._observer && element) {
  46600. this.camera.getScene().onPointerObservable.remove(this._observer);
  46601. this._observer = null;
  46602. this._wheel = null;
  46603. }
  46604. };
  46605. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46606. return "ArcRotateCameraMouseWheelInput";
  46607. };
  46608. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46609. return "mousewheel";
  46610. };
  46611. __decorate([
  46612. BABYLON.serialize()
  46613. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46614. __decorate([
  46615. BABYLON.serialize()
  46616. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46617. return ArcRotateCameraMouseWheelInput;
  46618. }());
  46619. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46620. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46621. })(BABYLON || (BABYLON = {}));
  46622. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46623. var BABYLON;
  46624. (function (BABYLON) {
  46625. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46626. function ArcRotateCameraPointersInput() {
  46627. this.buttons = [0, 1, 2];
  46628. this.angularSensibilityX = 1000.0;
  46629. this.angularSensibilityY = 1000.0;
  46630. this.pinchPrecision = 12.0;
  46631. /**
  46632. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46633. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46634. */
  46635. this.pinchDeltaPercentage = 0;
  46636. this.panningSensibility = 1000.0;
  46637. this.multiTouchPanning = true;
  46638. this.multiTouchPanAndZoom = true;
  46639. this._isPanClick = false;
  46640. this.pinchInwards = true;
  46641. }
  46642. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46643. var _this = this;
  46644. var engine = this.camera.getEngine();
  46645. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46646. var pointA = null;
  46647. var pointB = null;
  46648. var previousPinchSquaredDistance = 0;
  46649. var initialDistance = 0;
  46650. var twoFingerActivityCount = 0;
  46651. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46652. this._pointerInput = function (p, s) {
  46653. var evt = p.event;
  46654. var isTouch = p.event.pointerType === "touch";
  46655. if (engine.isInVRExclusivePointerMode) {
  46656. return;
  46657. }
  46658. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46659. return;
  46660. }
  46661. var srcElement = (evt.srcElement || evt.target);
  46662. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46663. try {
  46664. srcElement.setPointerCapture(evt.pointerId);
  46665. }
  46666. catch (e) {
  46667. //Nothing to do with the error. Execution will continue.
  46668. }
  46669. // Manage panning with pan button click
  46670. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46671. // manage pointers
  46672. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46673. if (pointA === null) {
  46674. pointA = cacheSoloPointer;
  46675. }
  46676. else if (pointB === null) {
  46677. pointB = cacheSoloPointer;
  46678. }
  46679. if (!noPreventDefault) {
  46680. evt.preventDefault();
  46681. element.focus();
  46682. }
  46683. }
  46684. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46685. _this.camera.restoreState();
  46686. }
  46687. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46688. try {
  46689. srcElement.releasePointerCapture(evt.pointerId);
  46690. }
  46691. catch (e) {
  46692. //Nothing to do with the error.
  46693. }
  46694. cacheSoloPointer = null;
  46695. previousPinchSquaredDistance = 0;
  46696. previousMultiTouchPanPosition.isPaning = false;
  46697. previousMultiTouchPanPosition.isPinching = false;
  46698. twoFingerActivityCount = 0;
  46699. initialDistance = 0;
  46700. if (!isTouch) {
  46701. pointB = null; // Mouse and pen are mono pointer
  46702. }
  46703. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46704. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46705. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46706. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  46707. if (engine._badOS) {
  46708. pointA = pointB = null;
  46709. }
  46710. else {
  46711. //only remove the impacted pointer in case of multitouch allowing on most
  46712. //platforms switching from rotate to zoom and pan seamlessly.
  46713. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  46714. pointA = pointB;
  46715. pointB = null;
  46716. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46717. }
  46718. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  46719. pointB = null;
  46720. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  46721. }
  46722. else {
  46723. pointA = pointB = null;
  46724. }
  46725. }
  46726. if (!noPreventDefault) {
  46727. evt.preventDefault();
  46728. }
  46729. }
  46730. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46731. if (!noPreventDefault) {
  46732. evt.preventDefault();
  46733. }
  46734. // One button down
  46735. if (pointA && pointB === null && cacheSoloPointer) {
  46736. if (_this.panningSensibility !== 0 &&
  46737. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  46738. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  46739. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  46740. }
  46741. else {
  46742. var offsetX = evt.clientX - cacheSoloPointer.x;
  46743. var offsetY = evt.clientY - cacheSoloPointer.y;
  46744. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46745. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46746. }
  46747. cacheSoloPointer.x = evt.clientX;
  46748. cacheSoloPointer.y = evt.clientY;
  46749. }
  46750. // Two buttons down: pinch/pan
  46751. else if (pointA && pointB) {
  46752. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  46753. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  46754. ed.x = evt.clientX;
  46755. ed.y = evt.clientY;
  46756. var direction = _this.pinchInwards ? 1 : -1;
  46757. var distX = pointA.x - pointB.x;
  46758. var distY = pointA.y - pointB.y;
  46759. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  46760. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  46761. if (previousPinchSquaredDistance === 0) {
  46762. initialDistance = pinchDistance;
  46763. previousPinchSquaredDistance = pinchSquaredDistance;
  46764. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  46765. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  46766. return;
  46767. }
  46768. if (_this.multiTouchPanAndZoom) {
  46769. if (_this.pinchDeltaPercentage) {
  46770. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46771. }
  46772. else {
  46773. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46774. (_this.pinchPrecision *
  46775. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46776. direction);
  46777. }
  46778. if (_this.panningSensibility !== 0) {
  46779. var pointersCenterX = (pointA.x + pointB.x) / 2;
  46780. var pointersCenterY = (pointA.y + pointB.y) / 2;
  46781. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  46782. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  46783. previousMultiTouchPanPosition.x = pointersCenterX;
  46784. previousMultiTouchPanPosition.y = pointersCenterY;
  46785. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  46786. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  46787. }
  46788. }
  46789. else {
  46790. twoFingerActivityCount++;
  46791. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  46792. if (_this.pinchDeltaPercentage) {
  46793. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  46794. }
  46795. else {
  46796. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  46797. (_this.pinchPrecision *
  46798. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  46799. direction);
  46800. }
  46801. previousMultiTouchPanPosition.isPaning = false;
  46802. previousMultiTouchPanPosition.isPinching = true;
  46803. }
  46804. else {
  46805. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  46806. if (!previousMultiTouchPanPosition.isPaning) {
  46807. previousMultiTouchPanPosition.isPaning = true;
  46808. previousMultiTouchPanPosition.isPinching = false;
  46809. previousMultiTouchPanPosition.x = ed.x;
  46810. previousMultiTouchPanPosition.y = ed.y;
  46811. return;
  46812. }
  46813. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  46814. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  46815. }
  46816. }
  46817. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  46818. previousMultiTouchPanPosition.x = ed.x;
  46819. previousMultiTouchPanPosition.y = ed.y;
  46820. }
  46821. }
  46822. previousPinchSquaredDistance = pinchSquaredDistance;
  46823. }
  46824. }
  46825. };
  46826. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  46827. this._onContextMenu = function (evt) {
  46828. evt.preventDefault();
  46829. };
  46830. if (!this.camera._useCtrlForPanning) {
  46831. element.addEventListener("contextmenu", this._onContextMenu, false);
  46832. }
  46833. this._onLostFocus = function () {
  46834. //this._keys = [];
  46835. pointA = pointB = null;
  46836. previousPinchSquaredDistance = 0;
  46837. previousMultiTouchPanPosition.isPaning = false;
  46838. previousMultiTouchPanPosition.isPinching = false;
  46839. twoFingerActivityCount = 0;
  46840. cacheSoloPointer = null;
  46841. initialDistance = 0;
  46842. };
  46843. this._onMouseMove = function (evt) {
  46844. if (!engine.isPointerLock) {
  46845. return;
  46846. }
  46847. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46848. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46849. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  46850. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  46851. if (!noPreventDefault) {
  46852. evt.preventDefault();
  46853. }
  46854. };
  46855. this._onGestureStart = function (e) {
  46856. if (window.MSGesture === undefined) {
  46857. return;
  46858. }
  46859. if (!_this._MSGestureHandler) {
  46860. _this._MSGestureHandler = new MSGesture();
  46861. _this._MSGestureHandler.target = element;
  46862. }
  46863. _this._MSGestureHandler.addPointer(e.pointerId);
  46864. };
  46865. this._onGesture = function (e) {
  46866. _this.camera.radius *= e.scale;
  46867. if (e.preventDefault) {
  46868. if (!noPreventDefault) {
  46869. e.stopPropagation();
  46870. e.preventDefault();
  46871. }
  46872. }
  46873. };
  46874. element.addEventListener("mousemove", this._onMouseMove, false);
  46875. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  46876. element.addEventListener("MSGestureChange", this._onGesture, false);
  46877. BABYLON.Tools.RegisterTopRootEvents([
  46878. { name: "blur", handler: this._onLostFocus }
  46879. ]);
  46880. };
  46881. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  46882. if (this._onLostFocus) {
  46883. BABYLON.Tools.UnregisterTopRootEvents([
  46884. { name: "blur", handler: this._onLostFocus }
  46885. ]);
  46886. }
  46887. if (element && this._observer) {
  46888. this.camera.getScene().onPointerObservable.remove(this._observer);
  46889. this._observer = null;
  46890. if (this._onContextMenu) {
  46891. element.removeEventListener("contextmenu", this._onContextMenu);
  46892. }
  46893. if (this._onMouseMove) {
  46894. element.removeEventListener("mousemove", this._onMouseMove);
  46895. }
  46896. if (this._onGestureStart) {
  46897. element.removeEventListener("MSPointerDown", this._onGestureStart);
  46898. }
  46899. if (this._onGesture) {
  46900. element.removeEventListener("MSGestureChange", this._onGesture);
  46901. }
  46902. this._isPanClick = false;
  46903. this.pinchInwards = true;
  46904. this._onMouseMove = null;
  46905. this._onGestureStart = null;
  46906. this._onGesture = null;
  46907. this._MSGestureHandler = null;
  46908. this._onLostFocus = null;
  46909. this._onContextMenu = null;
  46910. }
  46911. };
  46912. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  46913. return "ArcRotateCameraPointersInput";
  46914. };
  46915. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  46916. return "pointers";
  46917. };
  46918. __decorate([
  46919. BABYLON.serialize()
  46920. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  46924. __decorate([
  46925. BABYLON.serialize()
  46926. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  46927. __decorate([
  46928. BABYLON.serialize()
  46929. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  46930. __decorate([
  46931. BABYLON.serialize()
  46932. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  46933. __decorate([
  46934. BABYLON.serialize()
  46935. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  46936. __decorate([
  46937. BABYLON.serialize()
  46938. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  46939. __decorate([
  46940. BABYLON.serialize()
  46941. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  46942. return ArcRotateCameraPointersInput;
  46943. }());
  46944. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  46945. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  46946. })(BABYLON || (BABYLON = {}));
  46947. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  46948. var BABYLON;
  46949. (function (BABYLON) {
  46950. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  46951. __extends(ArcRotateCameraInputsManager, _super);
  46952. function ArcRotateCameraInputsManager(camera) {
  46953. return _super.call(this, camera) || this;
  46954. }
  46955. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  46956. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  46957. return this;
  46958. };
  46959. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  46960. this.add(new BABYLON.ArcRotateCameraPointersInput());
  46961. return this;
  46962. };
  46963. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  46964. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  46965. return this;
  46966. };
  46967. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  46968. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  46969. return this;
  46970. };
  46971. return ArcRotateCameraInputsManager;
  46972. }(BABYLON.CameraInputsManager));
  46973. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  46974. })(BABYLON || (BABYLON = {}));
  46975. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  46976. var BABYLON;
  46977. (function (BABYLON) {
  46978. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  46979. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  46980. });
  46981. var ArcRotateCamera = /** @class */ (function (_super) {
  46982. __extends(ArcRotateCamera, _super);
  46983. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  46984. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46985. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  46986. _this.inertialAlphaOffset = 0;
  46987. _this.inertialBetaOffset = 0;
  46988. _this.inertialRadiusOffset = 0;
  46989. _this.lowerAlphaLimit = null;
  46990. _this.upperAlphaLimit = null;
  46991. _this.lowerBetaLimit = 0.01;
  46992. _this.upperBetaLimit = Math.PI;
  46993. _this.lowerRadiusLimit = null;
  46994. _this.upperRadiusLimit = null;
  46995. _this.inertialPanningX = 0;
  46996. _this.inertialPanningY = 0;
  46997. _this.pinchToPanMaxDistance = 20;
  46998. _this.panningDistanceLimit = null;
  46999. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47000. _this.panningInertia = 0.9;
  47001. //-- end properties for backward compatibility for inputs
  47002. _this.zoomOnFactor = 1;
  47003. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47004. _this.allowUpsideDown = true;
  47005. _this._viewMatrix = new BABYLON.Matrix();
  47006. // Panning
  47007. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47008. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47009. _this.checkCollisions = false;
  47010. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47011. _this._previousPosition = BABYLON.Vector3.Zero();
  47012. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47013. _this._newPosition = BABYLON.Vector3.Zero();
  47014. _this._computationVector = BABYLON.Vector3.Zero();
  47015. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47016. if (collidedMesh === void 0) { collidedMesh = null; }
  47017. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47018. newPosition.multiplyInPlace(_this._collider._radius);
  47019. }
  47020. if (!collidedMesh) {
  47021. _this._previousPosition.copyFrom(_this.position);
  47022. }
  47023. else {
  47024. _this.setPosition(newPosition);
  47025. if (_this.onCollide) {
  47026. _this.onCollide(collidedMesh);
  47027. }
  47028. }
  47029. // Recompute because of constraints
  47030. var cosa = Math.cos(_this.alpha);
  47031. var sina = Math.sin(_this.alpha);
  47032. var cosb = Math.cos(_this.beta);
  47033. var sinb = Math.sin(_this.beta);
  47034. if (sinb === 0) {
  47035. sinb = 0.0001;
  47036. }
  47037. var target = _this._getTargetPosition();
  47038. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47039. target.addToRef(_this._computationVector, _this._newPosition);
  47040. _this.position.copyFrom(_this._newPosition);
  47041. var up = _this.upVector;
  47042. if (_this.allowUpsideDown && _this.beta < 0) {
  47043. up = up.clone();
  47044. up = up.negate();
  47045. }
  47046. _this._computeViewMatrix(_this.position, target, up);
  47047. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47048. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47049. _this._collisionTriggered = false;
  47050. };
  47051. _this._target = BABYLON.Vector3.Zero();
  47052. if (target) {
  47053. _this.setTarget(target);
  47054. }
  47055. _this.alpha = alpha;
  47056. _this.beta = beta;
  47057. _this.radius = radius;
  47058. _this.getViewMatrix();
  47059. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47060. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47061. return _this;
  47062. }
  47063. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47064. get: function () {
  47065. return this._target;
  47066. },
  47067. set: function (value) {
  47068. this.setTarget(value);
  47069. },
  47070. enumerable: true,
  47071. configurable: true
  47072. });
  47073. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47074. //-- begin properties for backward compatibility for inputs
  47075. get: function () {
  47076. var pointers = this.inputs.attached["pointers"];
  47077. if (pointers)
  47078. return pointers.angularSensibilityX;
  47079. return 0;
  47080. },
  47081. set: function (value) {
  47082. var pointers = this.inputs.attached["pointers"];
  47083. if (pointers) {
  47084. pointers.angularSensibilityX = value;
  47085. }
  47086. },
  47087. enumerable: true,
  47088. configurable: true
  47089. });
  47090. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47091. get: function () {
  47092. var pointers = this.inputs.attached["pointers"];
  47093. if (pointers)
  47094. return pointers.angularSensibilityY;
  47095. return 0;
  47096. },
  47097. set: function (value) {
  47098. var pointers = this.inputs.attached["pointers"];
  47099. if (pointers) {
  47100. pointers.angularSensibilityY = value;
  47101. }
  47102. },
  47103. enumerable: true,
  47104. configurable: true
  47105. });
  47106. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47107. get: function () {
  47108. var pointers = this.inputs.attached["pointers"];
  47109. if (pointers)
  47110. return pointers.pinchPrecision;
  47111. return 0;
  47112. },
  47113. set: function (value) {
  47114. var pointers = this.inputs.attached["pointers"];
  47115. if (pointers) {
  47116. pointers.pinchPrecision = value;
  47117. }
  47118. },
  47119. enumerable: true,
  47120. configurable: true
  47121. });
  47122. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47123. get: function () {
  47124. var pointers = this.inputs.attached["pointers"];
  47125. if (pointers)
  47126. return pointers.pinchDeltaPercentage;
  47127. return 0;
  47128. },
  47129. set: function (value) {
  47130. var pointers = this.inputs.attached["pointers"];
  47131. if (pointers) {
  47132. pointers.pinchDeltaPercentage = value;
  47133. }
  47134. },
  47135. enumerable: true,
  47136. configurable: true
  47137. });
  47138. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47139. get: function () {
  47140. var pointers = this.inputs.attached["pointers"];
  47141. if (pointers)
  47142. return pointers.panningSensibility;
  47143. return 0;
  47144. },
  47145. set: function (value) {
  47146. var pointers = this.inputs.attached["pointers"];
  47147. if (pointers) {
  47148. pointers.panningSensibility = value;
  47149. }
  47150. },
  47151. enumerable: true,
  47152. configurable: true
  47153. });
  47154. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47155. get: function () {
  47156. var keyboard = this.inputs.attached["keyboard"];
  47157. if (keyboard)
  47158. return keyboard.keysUp;
  47159. return [];
  47160. },
  47161. set: function (value) {
  47162. var keyboard = this.inputs.attached["keyboard"];
  47163. if (keyboard)
  47164. keyboard.keysUp = value;
  47165. },
  47166. enumerable: true,
  47167. configurable: true
  47168. });
  47169. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47170. get: function () {
  47171. var keyboard = this.inputs.attached["keyboard"];
  47172. if (keyboard)
  47173. return keyboard.keysDown;
  47174. return [];
  47175. },
  47176. set: function (value) {
  47177. var keyboard = this.inputs.attached["keyboard"];
  47178. if (keyboard)
  47179. keyboard.keysDown = value;
  47180. },
  47181. enumerable: true,
  47182. configurable: true
  47183. });
  47184. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47185. get: function () {
  47186. var keyboard = this.inputs.attached["keyboard"];
  47187. if (keyboard)
  47188. return keyboard.keysLeft;
  47189. return [];
  47190. },
  47191. set: function (value) {
  47192. var keyboard = this.inputs.attached["keyboard"];
  47193. if (keyboard)
  47194. keyboard.keysLeft = value;
  47195. },
  47196. enumerable: true,
  47197. configurable: true
  47198. });
  47199. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47200. get: function () {
  47201. var keyboard = this.inputs.attached["keyboard"];
  47202. if (keyboard)
  47203. return keyboard.keysRight;
  47204. return [];
  47205. },
  47206. set: function (value) {
  47207. var keyboard = this.inputs.attached["keyboard"];
  47208. if (keyboard)
  47209. keyboard.keysRight = value;
  47210. },
  47211. enumerable: true,
  47212. configurable: true
  47213. });
  47214. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47215. get: function () {
  47216. var mousewheel = this.inputs.attached["mousewheel"];
  47217. if (mousewheel)
  47218. return mousewheel.wheelPrecision;
  47219. return 0;
  47220. },
  47221. set: function (value) {
  47222. var mousewheel = this.inputs.attached["mousewheel"];
  47223. if (mousewheel)
  47224. mousewheel.wheelPrecision = value;
  47225. },
  47226. enumerable: true,
  47227. configurable: true
  47228. });
  47229. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47230. get: function () {
  47231. var mousewheel = this.inputs.attached["mousewheel"];
  47232. if (mousewheel)
  47233. return mousewheel.wheelDeltaPercentage;
  47234. return 0;
  47235. },
  47236. set: function (value) {
  47237. var mousewheel = this.inputs.attached["mousewheel"];
  47238. if (mousewheel)
  47239. mousewheel.wheelDeltaPercentage = value;
  47240. },
  47241. enumerable: true,
  47242. configurable: true
  47243. });
  47244. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47245. get: function () {
  47246. return this._bouncingBehavior;
  47247. },
  47248. enumerable: true,
  47249. configurable: true
  47250. });
  47251. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47252. get: function () {
  47253. return this._bouncingBehavior != null;
  47254. },
  47255. set: function (value) {
  47256. if (value === this.useBouncingBehavior) {
  47257. return;
  47258. }
  47259. if (value) {
  47260. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47261. this.addBehavior(this._bouncingBehavior);
  47262. }
  47263. else if (this._bouncingBehavior) {
  47264. this.removeBehavior(this._bouncingBehavior);
  47265. this._bouncingBehavior = null;
  47266. }
  47267. },
  47268. enumerable: true,
  47269. configurable: true
  47270. });
  47271. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47272. get: function () {
  47273. return this._framingBehavior;
  47274. },
  47275. enumerable: true,
  47276. configurable: true
  47277. });
  47278. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47279. get: function () {
  47280. return this._framingBehavior != null;
  47281. },
  47282. set: function (value) {
  47283. if (value === this.useFramingBehavior) {
  47284. return;
  47285. }
  47286. if (value) {
  47287. this._framingBehavior = new BABYLON.FramingBehavior();
  47288. this.addBehavior(this._framingBehavior);
  47289. }
  47290. else if (this._framingBehavior) {
  47291. this.removeBehavior(this._framingBehavior);
  47292. this._framingBehavior = null;
  47293. }
  47294. },
  47295. enumerable: true,
  47296. configurable: true
  47297. });
  47298. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47299. get: function () {
  47300. return this._autoRotationBehavior;
  47301. },
  47302. enumerable: true,
  47303. configurable: true
  47304. });
  47305. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47306. get: function () {
  47307. return this._autoRotationBehavior != null;
  47308. },
  47309. set: function (value) {
  47310. if (value === this.useAutoRotationBehavior) {
  47311. return;
  47312. }
  47313. if (value) {
  47314. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47315. this.addBehavior(this._autoRotationBehavior);
  47316. }
  47317. else if (this._autoRotationBehavior) {
  47318. this.removeBehavior(this._autoRotationBehavior);
  47319. this._autoRotationBehavior = null;
  47320. }
  47321. },
  47322. enumerable: true,
  47323. configurable: true
  47324. });
  47325. // Cache
  47326. ArcRotateCamera.prototype._initCache = function () {
  47327. _super.prototype._initCache.call(this);
  47328. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47329. this._cache.alpha = undefined;
  47330. this._cache.beta = undefined;
  47331. this._cache.radius = undefined;
  47332. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47333. };
  47334. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47335. if (!ignoreParentClass) {
  47336. _super.prototype._updateCache.call(this);
  47337. }
  47338. this._cache._target.copyFrom(this._getTargetPosition());
  47339. this._cache.alpha = this.alpha;
  47340. this._cache.beta = this.beta;
  47341. this._cache.radius = this.radius;
  47342. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47343. };
  47344. ArcRotateCamera.prototype._getTargetPosition = function () {
  47345. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47346. var pos = this._targetHost.getAbsolutePosition();
  47347. if (this._targetBoundingCenter) {
  47348. pos.addToRef(this._targetBoundingCenter, this._target);
  47349. }
  47350. else {
  47351. this._target.copyFrom(pos);
  47352. }
  47353. }
  47354. var lockedTargetPosition = this._getLockedTargetPosition();
  47355. if (lockedTargetPosition) {
  47356. return lockedTargetPosition;
  47357. }
  47358. return this._target;
  47359. };
  47360. ArcRotateCamera.prototype.storeState = function () {
  47361. this._storedAlpha = this.alpha;
  47362. this._storedBeta = this.beta;
  47363. this._storedRadius = this.radius;
  47364. this._storedTarget = this._getTargetPosition().clone();
  47365. return _super.prototype.storeState.call(this);
  47366. };
  47367. /**
  47368. * Restored camera state. You must call storeState() first
  47369. */
  47370. ArcRotateCamera.prototype._restoreStateValues = function () {
  47371. if (!_super.prototype._restoreStateValues.call(this)) {
  47372. return false;
  47373. }
  47374. this.alpha = this._storedAlpha;
  47375. this.beta = this._storedBeta;
  47376. this.radius = this._storedRadius;
  47377. this.setTarget(this._storedTarget.clone());
  47378. this.inertialAlphaOffset = 0;
  47379. this.inertialBetaOffset = 0;
  47380. this.inertialRadiusOffset = 0;
  47381. this.inertialPanningX = 0;
  47382. this.inertialPanningY = 0;
  47383. return true;
  47384. };
  47385. // Synchronized
  47386. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47387. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47388. return false;
  47389. return this._cache._target.equals(this._getTargetPosition())
  47390. && this._cache.alpha === this.alpha
  47391. && this._cache.beta === this.beta
  47392. && this._cache.radius === this.radius
  47393. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47394. };
  47395. // Methods
  47396. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47397. var _this = this;
  47398. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47399. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47400. this._useCtrlForPanning = useCtrlForPanning;
  47401. this._panningMouseButton = panningMouseButton;
  47402. this.inputs.attachElement(element, noPreventDefault);
  47403. this._reset = function () {
  47404. _this.inertialAlphaOffset = 0;
  47405. _this.inertialBetaOffset = 0;
  47406. _this.inertialRadiusOffset = 0;
  47407. _this.inertialPanningX = 0;
  47408. _this.inertialPanningY = 0;
  47409. };
  47410. };
  47411. ArcRotateCamera.prototype.detachControl = function (element) {
  47412. this.inputs.detachElement(element);
  47413. if (this._reset) {
  47414. this._reset();
  47415. }
  47416. };
  47417. ArcRotateCamera.prototype._checkInputs = function () {
  47418. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47419. if (this._collisionTriggered) {
  47420. return;
  47421. }
  47422. this.inputs.checkInputs();
  47423. // Inertia
  47424. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47425. var inertialAlphaOffset = this.inertialAlphaOffset;
  47426. if (this.beta <= 0)
  47427. inertialAlphaOffset *= -1;
  47428. if (this.getScene().useRightHandedSystem)
  47429. inertialAlphaOffset *= -1;
  47430. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47431. inertialAlphaOffset *= -1;
  47432. this.alpha += inertialAlphaOffset;
  47433. this.beta += this.inertialBetaOffset;
  47434. this.radius -= this.inertialRadiusOffset;
  47435. this.inertialAlphaOffset *= this.inertia;
  47436. this.inertialBetaOffset *= this.inertia;
  47437. this.inertialRadiusOffset *= this.inertia;
  47438. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47439. this.inertialAlphaOffset = 0;
  47440. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47441. this.inertialBetaOffset = 0;
  47442. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47443. this.inertialRadiusOffset = 0;
  47444. }
  47445. // Panning inertia
  47446. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47447. if (!this._localDirection) {
  47448. this._localDirection = BABYLON.Vector3.Zero();
  47449. this._transformedDirection = BABYLON.Vector3.Zero();
  47450. }
  47451. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47452. this._localDirection.multiplyInPlace(this.panningAxis);
  47453. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47454. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47455. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47456. if (!this.panningAxis.y) {
  47457. this._transformedDirection.y = 0;
  47458. }
  47459. if (!this._targetHost) {
  47460. if (this.panningDistanceLimit) {
  47461. this._transformedDirection.addInPlace(this._target);
  47462. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47463. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47464. this._target.copyFrom(this._transformedDirection);
  47465. }
  47466. }
  47467. else {
  47468. this._target.addInPlace(this._transformedDirection);
  47469. }
  47470. }
  47471. this.inertialPanningX *= this.panningInertia;
  47472. this.inertialPanningY *= this.panningInertia;
  47473. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47474. this.inertialPanningX = 0;
  47475. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47476. this.inertialPanningY = 0;
  47477. }
  47478. // Limits
  47479. this._checkLimits();
  47480. _super.prototype._checkInputs.call(this);
  47481. };
  47482. ArcRotateCamera.prototype._checkLimits = function () {
  47483. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47484. if (this.allowUpsideDown && this.beta > Math.PI) {
  47485. this.beta = this.beta - (2 * Math.PI);
  47486. }
  47487. }
  47488. else {
  47489. if (this.beta < this.lowerBetaLimit) {
  47490. this.beta = this.lowerBetaLimit;
  47491. }
  47492. }
  47493. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47494. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47495. this.beta = this.beta + (2 * Math.PI);
  47496. }
  47497. }
  47498. else {
  47499. if (this.beta > this.upperBetaLimit) {
  47500. this.beta = this.upperBetaLimit;
  47501. }
  47502. }
  47503. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47504. this.alpha = this.lowerAlphaLimit;
  47505. }
  47506. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47507. this.alpha = this.upperAlphaLimit;
  47508. }
  47509. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47510. this.radius = this.lowerRadiusLimit;
  47511. }
  47512. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47513. this.radius = this.upperRadiusLimit;
  47514. }
  47515. };
  47516. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47517. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47518. this.radius = this._computationVector.length();
  47519. if (this.radius === 0) {
  47520. this.radius = 0.0001; // Just to avoid division by zero
  47521. }
  47522. // Alpha
  47523. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47524. if (this._computationVector.z < 0) {
  47525. this.alpha = 2 * Math.PI - this.alpha;
  47526. }
  47527. // Beta
  47528. this.beta = Math.acos(this._computationVector.y / this.radius);
  47529. this._checkLimits();
  47530. };
  47531. ArcRotateCamera.prototype.setPosition = function (position) {
  47532. if (this.position.equals(position)) {
  47533. return;
  47534. }
  47535. this.position.copyFrom(position);
  47536. this.rebuildAnglesAndRadius();
  47537. };
  47538. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47539. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47540. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47541. if (target.getBoundingInfo) {
  47542. if (toBoundingCenter) {
  47543. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47544. }
  47545. else {
  47546. this._targetBoundingCenter = null;
  47547. }
  47548. this._targetHost = target;
  47549. this._target = this._getTargetPosition();
  47550. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47551. }
  47552. else {
  47553. var newTarget = target;
  47554. var currentTarget = this._getTargetPosition();
  47555. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47556. return;
  47557. }
  47558. this._targetHost = null;
  47559. this._target = newTarget;
  47560. this._targetBoundingCenter = null;
  47561. this.onMeshTargetChangedObservable.notifyObservers(null);
  47562. }
  47563. this.rebuildAnglesAndRadius();
  47564. };
  47565. ArcRotateCamera.prototype._getViewMatrix = function () {
  47566. // Compute
  47567. var cosa = Math.cos(this.alpha);
  47568. var sina = Math.sin(this.alpha);
  47569. var cosb = Math.cos(this.beta);
  47570. var sinb = Math.sin(this.beta);
  47571. if (sinb === 0) {
  47572. sinb = 0.0001;
  47573. }
  47574. var target = this._getTargetPosition();
  47575. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47576. target.addToRef(this._computationVector, this._newPosition);
  47577. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47578. if (!this._collider) {
  47579. this._collider = new BABYLON.Collider();
  47580. }
  47581. this._collider._radius = this.collisionRadius;
  47582. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47583. this._collisionTriggered = true;
  47584. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47585. }
  47586. else {
  47587. this.position.copyFrom(this._newPosition);
  47588. var up = this.upVector;
  47589. if (this.allowUpsideDown && sinb < 0) {
  47590. up = up.clone();
  47591. up = up.negate();
  47592. }
  47593. this._computeViewMatrix(this.position, target, up);
  47594. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47595. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47596. }
  47597. this._currentTarget = target;
  47598. return this._viewMatrix;
  47599. };
  47600. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47601. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47602. meshes = meshes || this.getScene().meshes;
  47603. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47604. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47605. this.radius = distance * this.zoomOnFactor;
  47606. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47607. };
  47608. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47609. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47610. var meshesOrMinMaxVector;
  47611. var distance;
  47612. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47613. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47614. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47615. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47616. }
  47617. else { //minMaxVector and distance
  47618. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47619. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47620. distance = minMaxVectorAndDistance.distance;
  47621. }
  47622. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47623. if (!doNotUpdateMaxZ) {
  47624. this.maxZ = distance * 2;
  47625. }
  47626. };
  47627. /**
  47628. * @override
  47629. * Override Camera.createRigCamera
  47630. */
  47631. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47632. var alphaShift = 0;
  47633. switch (this.cameraRigMode) {
  47634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47637. case BABYLON.Camera.RIG_MODE_VR:
  47638. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47639. break;
  47640. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47641. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47642. break;
  47643. }
  47644. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47645. rigCam._cameraRigParams = {};
  47646. return rigCam;
  47647. };
  47648. /**
  47649. * @override
  47650. * Override Camera._updateRigCameras
  47651. */
  47652. ArcRotateCamera.prototype._updateRigCameras = function () {
  47653. var camLeft = this._rigCameras[0];
  47654. var camRight = this._rigCameras[1];
  47655. camLeft.beta = camRight.beta = this.beta;
  47656. camLeft.radius = camRight.radius = this.radius;
  47657. switch (this.cameraRigMode) {
  47658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47661. case BABYLON.Camera.RIG_MODE_VR:
  47662. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47663. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47664. break;
  47665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47666. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47667. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47668. break;
  47669. }
  47670. _super.prototype._updateRigCameras.call(this);
  47671. };
  47672. ArcRotateCamera.prototype.dispose = function () {
  47673. this.inputs.clear();
  47674. _super.prototype.dispose.call(this);
  47675. };
  47676. ArcRotateCamera.prototype.getClassName = function () {
  47677. return "ArcRotateCamera";
  47678. };
  47679. __decorate([
  47680. BABYLON.serialize()
  47681. ], ArcRotateCamera.prototype, "alpha", void 0);
  47682. __decorate([
  47683. BABYLON.serialize()
  47684. ], ArcRotateCamera.prototype, "beta", void 0);
  47685. __decorate([
  47686. BABYLON.serialize()
  47687. ], ArcRotateCamera.prototype, "radius", void 0);
  47688. __decorate([
  47689. BABYLON.serializeAsVector3("target")
  47690. ], ArcRotateCamera.prototype, "_target", void 0);
  47691. __decorate([
  47692. BABYLON.serialize()
  47693. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47694. __decorate([
  47695. BABYLON.serialize()
  47696. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47697. __decorate([
  47698. BABYLON.serialize()
  47699. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47700. __decorate([
  47701. BABYLON.serialize()
  47702. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47703. __decorate([
  47704. BABYLON.serialize()
  47705. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47706. __decorate([
  47707. BABYLON.serialize()
  47708. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  47709. __decorate([
  47710. BABYLON.serialize()
  47711. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  47712. __decorate([
  47713. BABYLON.serialize()
  47714. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  47715. __decorate([
  47716. BABYLON.serialize()
  47717. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  47718. __decorate([
  47719. BABYLON.serialize()
  47720. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  47721. __decorate([
  47722. BABYLON.serialize()
  47723. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  47724. __decorate([
  47725. BABYLON.serialize()
  47726. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  47727. __decorate([
  47728. BABYLON.serialize()
  47729. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  47730. __decorate([
  47731. BABYLON.serializeAsVector3()
  47732. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  47733. __decorate([
  47734. BABYLON.serialize()
  47735. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  47736. __decorate([
  47737. BABYLON.serialize()
  47738. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  47739. __decorate([
  47740. BABYLON.serialize()
  47741. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  47742. return ArcRotateCamera;
  47743. }(BABYLON.TargetCamera));
  47744. BABYLON.ArcRotateCamera = ArcRotateCamera;
  47745. })(BABYLON || (BABYLON = {}));
  47746. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  47747. var BABYLON;
  47748. (function (BABYLON) {
  47749. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  47750. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  47751. });
  47752. /**
  47753. * The HemisphericLight simulates the ambient environment light,
  47754. * so the passed direction is the light reflection direction, not the incoming direction.
  47755. */
  47756. var HemisphericLight = /** @class */ (function (_super) {
  47757. __extends(HemisphericLight, _super);
  47758. /**
  47759. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  47760. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  47761. * The HemisphericLight can't cast shadows.
  47762. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47763. * @param name The friendly name of the light
  47764. * @param direction The direction of the light reflection
  47765. * @param scene The scene the light belongs to
  47766. */
  47767. function HemisphericLight(name, direction, scene) {
  47768. var _this = _super.call(this, name, scene) || this;
  47769. /**
  47770. * The groundColor is the light in the opposite direction to the one specified during creation.
  47771. * 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.
  47772. */
  47773. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  47774. _this.direction = direction || BABYLON.Vector3.Up();
  47775. return _this;
  47776. }
  47777. HemisphericLight.prototype._buildUniformLayout = function () {
  47778. this._uniformBuffer.addUniform("vLightData", 4);
  47779. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47780. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47781. this._uniformBuffer.addUniform("vLightGround", 3);
  47782. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47783. this._uniformBuffer.addUniform("depthValues", 2);
  47784. this._uniformBuffer.create();
  47785. };
  47786. /**
  47787. * Returns the string "HemisphericLight".
  47788. * @return The class name
  47789. */
  47790. HemisphericLight.prototype.getClassName = function () {
  47791. return "HemisphericLight";
  47792. };
  47793. /**
  47794. * Sets the HemisphericLight direction towards the passed target (Vector3).
  47795. * Returns the updated direction.
  47796. * @param target The target the direction should point to
  47797. * @return The computed direction
  47798. */
  47799. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  47800. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  47801. return this.direction;
  47802. };
  47803. /**
  47804. * Returns the shadow generator associated to the light.
  47805. * @returns Always null for hemispheric lights because it does not support shadows.
  47806. */
  47807. HemisphericLight.prototype.getShadowGenerator = function () {
  47808. return null;
  47809. };
  47810. /**
  47811. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  47812. * @param effect The effect to update
  47813. * @param lightIndex The index of the light in the effect to update
  47814. * @returns The hemispheric light
  47815. */
  47816. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  47817. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47818. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  47819. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  47820. return this;
  47821. };
  47822. /**
  47823. * @hidden internal use only.
  47824. */
  47825. HemisphericLight.prototype._getWorldMatrix = function () {
  47826. if (!this._worldMatrix) {
  47827. this._worldMatrix = BABYLON.Matrix.Identity();
  47828. }
  47829. return this._worldMatrix;
  47830. };
  47831. /**
  47832. * Returns the integer 3.
  47833. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47834. */
  47835. HemisphericLight.prototype.getTypeID = function () {
  47836. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  47837. };
  47838. /**
  47839. * Prepares the list of defines specific to the light type.
  47840. * @param defines the list of defines
  47841. * @param lightIndex defines the index of the light for the effect
  47842. */
  47843. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  47844. defines["HEMILIGHT" + lightIndex] = true;
  47845. };
  47846. __decorate([
  47847. BABYLON.serializeAsColor3()
  47848. ], HemisphericLight.prototype, "groundColor", void 0);
  47849. __decorate([
  47850. BABYLON.serializeAsVector3()
  47851. ], HemisphericLight.prototype, "direction", void 0);
  47852. return HemisphericLight;
  47853. }(BABYLON.Light));
  47854. BABYLON.HemisphericLight = HemisphericLight;
  47855. })(BABYLON || (BABYLON = {}));
  47856. //# sourceMappingURL=babylon.hemisphericLight.js.map
  47857. var BABYLON;
  47858. (function (BABYLON) {
  47859. /**
  47860. * Base implementation IShadowLight
  47861. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  47862. */
  47863. var ShadowLight = /** @class */ (function (_super) {
  47864. __extends(ShadowLight, _super);
  47865. function ShadowLight() {
  47866. var _this = _super !== null && _super.apply(this, arguments) || this;
  47867. _this._needProjectionMatrixCompute = true;
  47868. return _this;
  47869. }
  47870. ShadowLight.prototype._setPosition = function (value) {
  47871. this._position = value;
  47872. };
  47873. Object.defineProperty(ShadowLight.prototype, "position", {
  47874. /**
  47875. * Sets the position the shadow will be casted from. Also use as the light position for both
  47876. * point and spot lights.
  47877. */
  47878. get: function () {
  47879. return this._position;
  47880. },
  47881. /**
  47882. * Sets the position the shadow will be casted from. Also use as the light position for both
  47883. * point and spot lights.
  47884. */
  47885. set: function (value) {
  47886. this._setPosition(value);
  47887. },
  47888. enumerable: true,
  47889. configurable: true
  47890. });
  47891. ShadowLight.prototype._setDirection = function (value) {
  47892. this._direction = value;
  47893. };
  47894. Object.defineProperty(ShadowLight.prototype, "direction", {
  47895. /**
  47896. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  47897. * Also use as the light direction on spot and directional lights.
  47898. */
  47899. get: function () {
  47900. return this._direction;
  47901. },
  47902. /**
  47903. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  47904. * Also use as the light direction on spot and directional lights.
  47905. */
  47906. set: function (value) {
  47907. this._setDirection(value);
  47908. },
  47909. enumerable: true,
  47910. configurable: true
  47911. });
  47912. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  47913. /**
  47914. * Gets the shadow projection clipping minimum z value.
  47915. */
  47916. get: function () {
  47917. return this._shadowMinZ;
  47918. },
  47919. /**
  47920. * Sets the shadow projection clipping minimum z value.
  47921. */
  47922. set: function (value) {
  47923. this._shadowMinZ = value;
  47924. this.forceProjectionMatrixCompute();
  47925. },
  47926. enumerable: true,
  47927. configurable: true
  47928. });
  47929. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  47930. /**
  47931. * Sets the shadow projection clipping maximum z value.
  47932. */
  47933. get: function () {
  47934. return this._shadowMaxZ;
  47935. },
  47936. /**
  47937. * Gets the shadow projection clipping maximum z value.
  47938. */
  47939. set: function (value) {
  47940. this._shadowMaxZ = value;
  47941. this.forceProjectionMatrixCompute();
  47942. },
  47943. enumerable: true,
  47944. configurable: true
  47945. });
  47946. /**
  47947. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  47948. * @returns true if the information has been computed, false if it does not need to (no parenting)
  47949. */
  47950. ShadowLight.prototype.computeTransformedInformation = function () {
  47951. if (this.parent && this.parent.getWorldMatrix) {
  47952. if (!this.transformedPosition) {
  47953. this.transformedPosition = BABYLON.Vector3.Zero();
  47954. }
  47955. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  47956. // In case the direction is present.
  47957. if (this.direction) {
  47958. if (!this.transformedDirection) {
  47959. this.transformedDirection = BABYLON.Vector3.Zero();
  47960. }
  47961. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  47962. }
  47963. return true;
  47964. }
  47965. return false;
  47966. };
  47967. /**
  47968. * Return the depth scale used for the shadow map.
  47969. * @returns the depth scale.
  47970. */
  47971. ShadowLight.prototype.getDepthScale = function () {
  47972. return 50.0;
  47973. };
  47974. /**
  47975. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  47976. * @param faceIndex The index of the face we are computed the direction to generate shadow
  47977. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  47978. */
  47979. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  47980. return this.transformedDirection ? this.transformedDirection : this.direction;
  47981. };
  47982. /**
  47983. * Returns the ShadowLight absolute position in the World.
  47984. * @returns the position vector in world space
  47985. */
  47986. ShadowLight.prototype.getAbsolutePosition = function () {
  47987. return this.transformedPosition ? this.transformedPosition : this.position;
  47988. };
  47989. /**
  47990. * Sets the ShadowLight direction toward the passed target.
  47991. * @param target The point tot target in local space
  47992. * @returns the updated ShadowLight direction
  47993. */
  47994. ShadowLight.prototype.setDirectionToTarget = function (target) {
  47995. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  47996. return this.direction;
  47997. };
  47998. /**
  47999. * Returns the light rotation in euler definition.
  48000. * @returns the x y z rotation in local space.
  48001. */
  48002. ShadowLight.prototype.getRotation = function () {
  48003. this.direction.normalize();
  48004. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48005. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48006. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48007. };
  48008. /**
  48009. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48010. * @returns true if a cube texture needs to be use
  48011. */
  48012. ShadowLight.prototype.needCube = function () {
  48013. return false;
  48014. };
  48015. /**
  48016. * Detects if the projection matrix requires to be recomputed this frame.
  48017. * @returns true if it requires to be recomputed otherwise, false.
  48018. */
  48019. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48020. return this._needProjectionMatrixCompute;
  48021. };
  48022. /**
  48023. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48024. */
  48025. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48026. this._needProjectionMatrixCompute = true;
  48027. };
  48028. /**
  48029. * Get the world matrix of the sahdow lights.
  48030. * @hidden Internal Use Only
  48031. */
  48032. ShadowLight.prototype._getWorldMatrix = function () {
  48033. if (!this._worldMatrix) {
  48034. this._worldMatrix = BABYLON.Matrix.Identity();
  48035. }
  48036. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48037. return this._worldMatrix;
  48038. };
  48039. /**
  48040. * Gets the minZ used for shadow according to both the scene and the light.
  48041. * @param activeCamera The camera we are returning the min for
  48042. * @returns the depth min z
  48043. */
  48044. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48045. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48046. };
  48047. /**
  48048. * Gets the maxZ used for shadow according to both the scene and the light.
  48049. * @param activeCamera The camera we are returning the max for
  48050. * @returns the depth max z
  48051. */
  48052. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48053. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48054. };
  48055. /**
  48056. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48057. * @param matrix The materix to updated with the projection information
  48058. * @param viewMatrix The transform matrix of the light
  48059. * @param renderList The list of mesh to render in the map
  48060. * @returns The current light
  48061. */
  48062. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48063. if (this.customProjectionMatrixBuilder) {
  48064. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48065. }
  48066. else {
  48067. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48068. }
  48069. return this;
  48070. };
  48071. __decorate([
  48072. BABYLON.serializeAsVector3()
  48073. ], ShadowLight.prototype, "position", null);
  48074. __decorate([
  48075. BABYLON.serializeAsVector3()
  48076. ], ShadowLight.prototype, "direction", null);
  48077. __decorate([
  48078. BABYLON.serialize()
  48079. ], ShadowLight.prototype, "shadowMinZ", null);
  48080. __decorate([
  48081. BABYLON.serialize()
  48082. ], ShadowLight.prototype, "shadowMaxZ", null);
  48083. return ShadowLight;
  48084. }(BABYLON.Light));
  48085. BABYLON.ShadowLight = ShadowLight;
  48086. })(BABYLON || (BABYLON = {}));
  48087. //# sourceMappingURL=babylon.shadowLight.js.map
  48088. var BABYLON;
  48089. (function (BABYLON) {
  48090. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48091. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48092. });
  48093. /**
  48094. * A point light is a light defined by an unique point in world space.
  48095. * The light is emitted in every direction from this point.
  48096. * A good example of a point light is a standard light bulb.
  48097. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48098. */
  48099. var PointLight = /** @class */ (function (_super) {
  48100. __extends(PointLight, _super);
  48101. /**
  48102. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48103. * A PointLight emits the light in every direction.
  48104. * It can cast shadows.
  48105. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48106. * ```javascript
  48107. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48108. * ```
  48109. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48110. * @param name The light friendly name
  48111. * @param position The position of the point light in the scene
  48112. * @param scene The scene the lights belongs to
  48113. */
  48114. function PointLight(name, position, scene) {
  48115. var _this = _super.call(this, name, scene) || this;
  48116. _this._shadowAngle = Math.PI / 2;
  48117. _this.position = position;
  48118. return _this;
  48119. }
  48120. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48121. /**
  48122. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48123. * This specifies what angle the shadow will use to be created.
  48124. *
  48125. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48126. */
  48127. get: function () {
  48128. return this._shadowAngle;
  48129. },
  48130. /**
  48131. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48132. * This specifies what angle the shadow will use to be created.
  48133. *
  48134. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48135. */
  48136. set: function (value) {
  48137. this._shadowAngle = value;
  48138. this.forceProjectionMatrixCompute();
  48139. },
  48140. enumerable: true,
  48141. configurable: true
  48142. });
  48143. Object.defineProperty(PointLight.prototype, "direction", {
  48144. /**
  48145. * Gets the direction if it has been set.
  48146. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48147. */
  48148. get: function () {
  48149. return this._direction;
  48150. },
  48151. /**
  48152. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48153. */
  48154. set: function (value) {
  48155. var previousNeedCube = this.needCube();
  48156. this._direction = value;
  48157. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48158. this._shadowGenerator.recreateShadowMap();
  48159. }
  48160. },
  48161. enumerable: true,
  48162. configurable: true
  48163. });
  48164. /**
  48165. * Returns the string "PointLight"
  48166. * @returns the class name
  48167. */
  48168. PointLight.prototype.getClassName = function () {
  48169. return "PointLight";
  48170. };
  48171. /**
  48172. * Returns the integer 0.
  48173. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48174. */
  48175. PointLight.prototype.getTypeID = function () {
  48176. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48177. };
  48178. /**
  48179. * Specifies wether or not the shadowmap should be a cube texture.
  48180. * @returns true if the shadowmap needs to be a cube texture.
  48181. */
  48182. PointLight.prototype.needCube = function () {
  48183. return !this.direction;
  48184. };
  48185. /**
  48186. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48187. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48188. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48189. */
  48190. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48191. if (this.direction) {
  48192. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48193. }
  48194. else {
  48195. switch (faceIndex) {
  48196. case 0:
  48197. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48198. case 1:
  48199. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48200. case 2:
  48201. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48202. case 3:
  48203. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48204. case 4:
  48205. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48206. case 5:
  48207. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48208. }
  48209. }
  48210. return BABYLON.Vector3.Zero();
  48211. };
  48212. /**
  48213. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48214. * - fov = PI / 2
  48215. * - aspect ratio : 1.0
  48216. * - z-near and far equal to the active camera minZ and maxZ.
  48217. * Returns the PointLight.
  48218. */
  48219. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48220. var activeCamera = this.getScene().activeCamera;
  48221. if (!activeCamera) {
  48222. return;
  48223. }
  48224. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48225. };
  48226. PointLight.prototype._buildUniformLayout = function () {
  48227. this._uniformBuffer.addUniform("vLightData", 4);
  48228. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48229. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48230. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48231. this._uniformBuffer.addUniform("depthValues", 2);
  48232. this._uniformBuffer.create();
  48233. };
  48234. /**
  48235. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48236. * @param effect The effect to update
  48237. * @param lightIndex The index of the light in the effect to update
  48238. * @returns The point light
  48239. */
  48240. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48241. if (this.computeTransformedInformation()) {
  48242. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48243. return this;
  48244. }
  48245. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48246. return this;
  48247. };
  48248. /**
  48249. * Prepares the list of defines specific to the light type.
  48250. * @param defines the list of defines
  48251. * @param lightIndex defines the index of the light for the effect
  48252. */
  48253. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48254. defines["POINTLIGHT" + lightIndex] = true;
  48255. };
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], PointLight.prototype, "shadowAngle", null);
  48259. return PointLight;
  48260. }(BABYLON.ShadowLight));
  48261. BABYLON.PointLight = PointLight;
  48262. })(BABYLON || (BABYLON = {}));
  48263. //# sourceMappingURL=babylon.pointLight.js.map
  48264. var BABYLON;
  48265. (function (BABYLON) {
  48266. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48267. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48268. });
  48269. /**
  48270. * A directional light is defined by a direction (what a surprise!).
  48271. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48272. * 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.
  48273. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48274. */
  48275. var DirectionalLight = /** @class */ (function (_super) {
  48276. __extends(DirectionalLight, _super);
  48277. /**
  48278. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48279. * The directional light is emitted from everywhere in the given direction.
  48280. * It can cast shawdows.
  48281. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48282. * @param name The friendly name of the light
  48283. * @param direction The direction of the light
  48284. * @param scene The scene the light belongs to
  48285. */
  48286. function DirectionalLight(name, direction, scene) {
  48287. var _this = _super.call(this, name, scene) || this;
  48288. _this._shadowFrustumSize = 0;
  48289. _this._shadowOrthoScale = 0.1;
  48290. /**
  48291. * Automatically compute the projection matrix to best fit (including all the casters)
  48292. * on each frame.
  48293. */
  48294. _this.autoUpdateExtends = true;
  48295. // Cache
  48296. _this._orthoLeft = Number.MAX_VALUE;
  48297. _this._orthoRight = Number.MIN_VALUE;
  48298. _this._orthoTop = Number.MIN_VALUE;
  48299. _this._orthoBottom = Number.MAX_VALUE;
  48300. _this.position = direction.scale(-1.0);
  48301. _this.direction = direction;
  48302. return _this;
  48303. }
  48304. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48305. /**
  48306. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48307. */
  48308. get: function () {
  48309. return this._shadowFrustumSize;
  48310. },
  48311. /**
  48312. * Specifies a fix frustum size for the shadow generation.
  48313. */
  48314. set: function (value) {
  48315. this._shadowFrustumSize = value;
  48316. this.forceProjectionMatrixCompute();
  48317. },
  48318. enumerable: true,
  48319. configurable: true
  48320. });
  48321. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48322. /**
  48323. * Gets the shadow projection scale against the optimal computed one.
  48324. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48325. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48326. */
  48327. get: function () {
  48328. return this._shadowOrthoScale;
  48329. },
  48330. /**
  48331. * Sets the shadow projection scale against the optimal computed one.
  48332. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48333. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48334. */
  48335. set: function (value) {
  48336. this._shadowOrthoScale = value;
  48337. this.forceProjectionMatrixCompute();
  48338. },
  48339. enumerable: true,
  48340. configurable: true
  48341. });
  48342. /**
  48343. * Returns the string "DirectionalLight".
  48344. * @return The class name
  48345. */
  48346. DirectionalLight.prototype.getClassName = function () {
  48347. return "DirectionalLight";
  48348. };
  48349. /**
  48350. * Returns the integer 1.
  48351. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48352. */
  48353. DirectionalLight.prototype.getTypeID = function () {
  48354. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48355. };
  48356. /**
  48357. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48358. * Returns the DirectionalLight Shadow projection matrix.
  48359. */
  48360. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48361. if (this.shadowFrustumSize > 0) {
  48362. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48363. }
  48364. else {
  48365. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48366. }
  48367. };
  48368. /**
  48369. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48370. * Returns the DirectionalLight Shadow projection matrix.
  48371. */
  48372. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48373. var activeCamera = this.getScene().activeCamera;
  48374. if (!activeCamera) {
  48375. return;
  48376. }
  48377. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48378. };
  48379. /**
  48380. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48381. * Returns the DirectionalLight Shadow projection matrix.
  48382. */
  48383. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48384. var activeCamera = this.getScene().activeCamera;
  48385. if (!activeCamera) {
  48386. return;
  48387. }
  48388. // Check extends
  48389. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48390. var tempVector3 = BABYLON.Vector3.Zero();
  48391. this._orthoLeft = Number.MAX_VALUE;
  48392. this._orthoRight = Number.MIN_VALUE;
  48393. this._orthoTop = Number.MIN_VALUE;
  48394. this._orthoBottom = Number.MAX_VALUE;
  48395. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48396. var mesh = renderList[meshIndex];
  48397. if (!mesh) {
  48398. continue;
  48399. }
  48400. var boundingInfo = mesh.getBoundingInfo();
  48401. var boundingBox = boundingInfo.boundingBox;
  48402. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48403. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48404. if (tempVector3.x < this._orthoLeft)
  48405. this._orthoLeft = tempVector3.x;
  48406. if (tempVector3.y < this._orthoBottom)
  48407. this._orthoBottom = tempVector3.y;
  48408. if (tempVector3.x > this._orthoRight)
  48409. this._orthoRight = tempVector3.x;
  48410. if (tempVector3.y > this._orthoTop)
  48411. this._orthoTop = tempVector3.y;
  48412. }
  48413. }
  48414. }
  48415. var xOffset = this._orthoRight - this._orthoLeft;
  48416. var yOffset = this._orthoTop - this._orthoBottom;
  48417. 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);
  48418. };
  48419. DirectionalLight.prototype._buildUniformLayout = function () {
  48420. this._uniformBuffer.addUniform("vLightData", 4);
  48421. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48422. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48423. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48424. this._uniformBuffer.addUniform("depthValues", 2);
  48425. this._uniformBuffer.create();
  48426. };
  48427. /**
  48428. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48429. * @param effect The effect to update
  48430. * @param lightIndex The index of the light in the effect to update
  48431. * @returns The directional light
  48432. */
  48433. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48434. if (this.computeTransformedInformation()) {
  48435. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48436. return this;
  48437. }
  48438. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48439. return this;
  48440. };
  48441. /**
  48442. * Gets the minZ used for shadow according to both the scene and the light.
  48443. *
  48444. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48445. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48446. * @param activeCamera The camera we are returning the min for
  48447. * @returns the depth min z
  48448. */
  48449. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48450. return 1;
  48451. };
  48452. /**
  48453. * Gets the maxZ used for shadow according to both the scene and the light.
  48454. *
  48455. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48456. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48457. * @param activeCamera The camera we are returning the max for
  48458. * @returns the depth max z
  48459. */
  48460. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48461. return 1;
  48462. };
  48463. /**
  48464. * Prepares the list of defines specific to the light type.
  48465. * @param defines the list of defines
  48466. * @param lightIndex defines the index of the light for the effect
  48467. */
  48468. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48469. defines["DIRLIGHT" + lightIndex] = true;
  48470. };
  48471. __decorate([
  48472. BABYLON.serialize()
  48473. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48474. __decorate([
  48475. BABYLON.serialize()
  48476. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48477. __decorate([
  48478. BABYLON.serialize()
  48479. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48480. return DirectionalLight;
  48481. }(BABYLON.ShadowLight));
  48482. BABYLON.DirectionalLight = DirectionalLight;
  48483. })(BABYLON || (BABYLON = {}));
  48484. //# sourceMappingURL=babylon.directionalLight.js.map
  48485. var BABYLON;
  48486. (function (BABYLON) {
  48487. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48488. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48489. });
  48490. /**
  48491. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48492. * These values define a cone of light starting from the position, emitting toward the direction.
  48493. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48494. * and the exponent defines the speed of the decay of the light with distance (reach).
  48495. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48496. */
  48497. var SpotLight = /** @class */ (function (_super) {
  48498. __extends(SpotLight, _super);
  48499. /**
  48500. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48501. * It can cast shadows.
  48502. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48503. * @param name The light friendly name
  48504. * @param position The position of the spot light in the scene
  48505. * @param direction The direction of the light in the scene
  48506. * @param angle The cone angle of the light in Radians
  48507. * @param exponent The light decay speed with the distance from the emission spot
  48508. * @param scene The scene the lights belongs to
  48509. */
  48510. function SpotLight(name, position, direction, angle, exponent, scene) {
  48511. var _this = _super.call(this, name, scene) || this;
  48512. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48513. _this._projectionTextureLightNear = 1e-6;
  48514. _this._projectionTextureLightFar = 1000.0;
  48515. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48516. _this._projectionTextureViewLightDirty = true;
  48517. _this._projectionTextureProjectionLightDirty = true;
  48518. _this._projectionTextureDirty = true;
  48519. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48520. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48521. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48522. _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);
  48523. _this.position = position;
  48524. _this.direction = direction;
  48525. _this.angle = angle;
  48526. _this.exponent = exponent;
  48527. return _this;
  48528. }
  48529. Object.defineProperty(SpotLight.prototype, "angle", {
  48530. /**
  48531. * Gets the cone angle of the spot light in Radians.
  48532. */
  48533. get: function () {
  48534. return this._angle;
  48535. },
  48536. /**
  48537. * Sets the cone angle of the spot light in Radians.
  48538. */
  48539. set: function (value) {
  48540. this._angle = value;
  48541. this._projectionTextureProjectionLightDirty = true;
  48542. this.forceProjectionMatrixCompute();
  48543. },
  48544. enumerable: true,
  48545. configurable: true
  48546. });
  48547. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48548. /**
  48549. * Allows scaling the angle of the light for shadow generation only.
  48550. */
  48551. get: function () {
  48552. return this._shadowAngleScale;
  48553. },
  48554. /**
  48555. * Allows scaling the angle of the light for shadow generation only.
  48556. */
  48557. set: function (value) {
  48558. this._shadowAngleScale = value;
  48559. this.forceProjectionMatrixCompute();
  48560. },
  48561. enumerable: true,
  48562. configurable: true
  48563. });
  48564. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48565. /**
  48566. * Allows reading the projecton texture
  48567. */
  48568. get: function () {
  48569. return this._projectionTextureMatrix;
  48570. },
  48571. enumerable: true,
  48572. configurable: true
  48573. });
  48574. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48575. /**
  48576. * Gets the near clip of the Spotlight for texture projection.
  48577. */
  48578. get: function () {
  48579. return this._projectionTextureLightNear;
  48580. },
  48581. /**
  48582. * Sets the near clip of the Spotlight for texture projection.
  48583. */
  48584. set: function (value) {
  48585. this._projectionTextureLightNear = value;
  48586. this._projectionTextureProjectionLightDirty = true;
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48592. /**
  48593. * Gets the far clip of the Spotlight for texture projection.
  48594. */
  48595. get: function () {
  48596. return this._projectionTextureLightFar;
  48597. },
  48598. /**
  48599. * Sets the far clip of the Spotlight for texture projection.
  48600. */
  48601. set: function (value) {
  48602. this._projectionTextureLightFar = value;
  48603. this._projectionTextureProjectionLightDirty = true;
  48604. },
  48605. enumerable: true,
  48606. configurable: true
  48607. });
  48608. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48609. /**
  48610. * Gets the Up vector of the Spotlight for texture projection.
  48611. */
  48612. get: function () {
  48613. return this._projectionTextureUpDirection;
  48614. },
  48615. /**
  48616. * Sets the Up vector of the Spotlight for texture projection.
  48617. */
  48618. set: function (value) {
  48619. this._projectionTextureUpDirection = value;
  48620. this._projectionTextureProjectionLightDirty = true;
  48621. },
  48622. enumerable: true,
  48623. configurable: true
  48624. });
  48625. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48626. /**
  48627. * Gets the projection texture of the light.
  48628. */
  48629. get: function () {
  48630. return this._projectionTexture;
  48631. },
  48632. /**
  48633. * Sets the projection texture of the light.
  48634. */
  48635. set: function (value) {
  48636. this._projectionTexture = value;
  48637. this._projectionTextureDirty = true;
  48638. },
  48639. enumerable: true,
  48640. configurable: true
  48641. });
  48642. /**
  48643. * Returns the string "SpotLight".
  48644. * @returns the class name
  48645. */
  48646. SpotLight.prototype.getClassName = function () {
  48647. return "SpotLight";
  48648. };
  48649. /**
  48650. * Returns the integer 2.
  48651. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48652. */
  48653. SpotLight.prototype.getTypeID = function () {
  48654. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48655. };
  48656. /**
  48657. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48658. */
  48659. SpotLight.prototype._setDirection = function (value) {
  48660. _super.prototype._setDirection.call(this, value);
  48661. this._projectionTextureViewLightDirty = true;
  48662. };
  48663. /**
  48664. * Overrides the position setter to recompute the projection texture view light Matrix.
  48665. */
  48666. SpotLight.prototype._setPosition = function (value) {
  48667. _super.prototype._setPosition.call(this, value);
  48668. this._projectionTextureViewLightDirty = true;
  48669. };
  48670. /**
  48671. * 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.
  48672. * Returns the SpotLight.
  48673. */
  48674. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48675. var activeCamera = this.getScene().activeCamera;
  48676. if (!activeCamera) {
  48677. return;
  48678. }
  48679. this._shadowAngleScale = this._shadowAngleScale || 1;
  48680. var angle = this._shadowAngleScale * this._angle;
  48681. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48682. };
  48683. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48684. this._projectionTextureViewLightDirty = false;
  48685. this._projectionTextureDirty = true;
  48686. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48687. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48688. };
  48689. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48690. this._projectionTextureProjectionLightDirty = false;
  48691. this._projectionTextureDirty = true;
  48692. var light_far = this.projectionTextureLightFar;
  48693. var light_near = this.projectionTextureLightNear;
  48694. var P = light_far / (light_far - light_near);
  48695. var Q = -P * light_near;
  48696. var S = 1.0 / Math.tan(this._angle / 2.0);
  48697. var A = 1.0;
  48698. 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);
  48699. };
  48700. /**
  48701. * Main function for light texture projection matrix computing.
  48702. */
  48703. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48704. this._projectionTextureDirty = false;
  48705. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48706. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  48707. };
  48708. SpotLight.prototype._buildUniformLayout = function () {
  48709. this._uniformBuffer.addUniform("vLightData", 4);
  48710. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48711. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48712. this._uniformBuffer.addUniform("vLightDirection", 3);
  48713. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48714. this._uniformBuffer.addUniform("depthValues", 2);
  48715. this._uniformBuffer.create();
  48716. };
  48717. /**
  48718. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  48719. * @param effect The effect to update
  48720. * @param lightIndex The index of the light in the effect to update
  48721. * @returns The spot light
  48722. */
  48723. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  48724. var normalizeDirection;
  48725. if (this.computeTransformedInformation()) {
  48726. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  48727. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  48728. }
  48729. else {
  48730. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  48731. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48732. }
  48733. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  48734. if (this.projectionTexture && this.projectionTexture.isReady()) {
  48735. if (this._projectionTextureViewLightDirty) {
  48736. this._computeProjectionTextureViewLightMatrix();
  48737. }
  48738. if (this._projectionTextureProjectionLightDirty) {
  48739. this._computeProjectionTextureProjectionLightMatrix();
  48740. }
  48741. if (this._projectionTextureDirty) {
  48742. this._computeProjectionTextureMatrix();
  48743. }
  48744. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  48745. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  48746. }
  48747. return this;
  48748. };
  48749. /**
  48750. * Disposes the light and the associated resources.
  48751. */
  48752. SpotLight.prototype.dispose = function () {
  48753. _super.prototype.dispose.call(this);
  48754. if (this._projectionTexture) {
  48755. this._projectionTexture.dispose();
  48756. }
  48757. };
  48758. /**
  48759. * Prepares the list of defines specific to the light type.
  48760. * @param defines the list of defines
  48761. * @param lightIndex defines the index of the light for the effect
  48762. */
  48763. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48764. defines["SPOTLIGHT" + lightIndex] = true;
  48765. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  48766. };
  48767. __decorate([
  48768. BABYLON.serialize()
  48769. ], SpotLight.prototype, "angle", null);
  48770. __decorate([
  48771. BABYLON.serialize()
  48772. ], SpotLight.prototype, "shadowAngleScale", null);
  48773. __decorate([
  48774. BABYLON.serialize()
  48775. ], SpotLight.prototype, "exponent", void 0);
  48776. __decorate([
  48777. BABYLON.serialize()
  48778. ], SpotLight.prototype, "projectionTextureLightNear", null);
  48779. __decorate([
  48780. BABYLON.serialize()
  48781. ], SpotLight.prototype, "projectionTextureLightFar", null);
  48782. __decorate([
  48783. BABYLON.serialize()
  48784. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  48785. __decorate([
  48786. BABYLON.serializeAsTexture("projectedLightTexture")
  48787. ], SpotLight.prototype, "_projectionTexture", void 0);
  48788. return SpotLight;
  48789. }(BABYLON.ShadowLight));
  48790. BABYLON.SpotLight = SpotLight;
  48791. })(BABYLON || (BABYLON = {}));
  48792. //# sourceMappingURL=babylon.spotLight.js.map
  48793. var BABYLON;
  48794. (function (BABYLON) {
  48795. /**
  48796. * Class used to override all child animations of a given target
  48797. */
  48798. var AnimationPropertiesOverride = /** @class */ (function () {
  48799. function AnimationPropertiesOverride() {
  48800. /**
  48801. * Gets or sets a value indicating if animation blending must be used
  48802. */
  48803. this.enableBlending = false;
  48804. /**
  48805. * Gets or sets the blending speed to use when enableBlending is true
  48806. */
  48807. this.blendingSpeed = 0.01;
  48808. /**
  48809. * Gets or sets the default loop mode to use
  48810. */
  48811. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  48812. }
  48813. return AnimationPropertiesOverride;
  48814. }());
  48815. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  48816. })(BABYLON || (BABYLON = {}));
  48817. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  48818. var BABYLON;
  48819. (function (BABYLON) {
  48820. /**
  48821. * Represents the range of an animation
  48822. */
  48823. var AnimationRange = /** @class */ (function () {
  48824. /**
  48825. * Initializes the range of an animation
  48826. * @param name The name of the animation range
  48827. * @param from The starting frame of the animation
  48828. * @param to The ending frame of the animation
  48829. */
  48830. function AnimationRange(
  48831. /**The name of the animation range**/
  48832. name,
  48833. /**The starting frame of the animation */
  48834. from,
  48835. /**The ending frame of the animation*/
  48836. to) {
  48837. this.name = name;
  48838. this.from = from;
  48839. this.to = to;
  48840. }
  48841. /**
  48842. * Makes a copy of the animation range
  48843. * @returns A copy of the animation range
  48844. */
  48845. AnimationRange.prototype.clone = function () {
  48846. return new AnimationRange(this.name, this.from, this.to);
  48847. };
  48848. return AnimationRange;
  48849. }());
  48850. BABYLON.AnimationRange = AnimationRange;
  48851. /**
  48852. * Composed of a frame, and an action function
  48853. */
  48854. var AnimationEvent = /** @class */ (function () {
  48855. /**
  48856. * Initializes the animation event
  48857. * @param frame The frame for which the event is triggered
  48858. * @param action The event to perform when triggered
  48859. * @param onlyOnce Specifies if the event should be triggered only once
  48860. */
  48861. function AnimationEvent(
  48862. /** The frame for which the event is triggered **/
  48863. frame,
  48864. /** The event to perform when triggered **/
  48865. action,
  48866. /** Specifies if the event should be triggered only once**/
  48867. onlyOnce) {
  48868. this.frame = frame;
  48869. this.action = action;
  48870. this.onlyOnce = onlyOnce;
  48871. /**
  48872. * Specifies if the animation event is done
  48873. */
  48874. this.isDone = false;
  48875. }
  48876. /** @hidden */
  48877. AnimationEvent.prototype._clone = function () {
  48878. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  48879. };
  48880. return AnimationEvent;
  48881. }());
  48882. BABYLON.AnimationEvent = AnimationEvent;
  48883. /**
  48884. * A cursor which tracks a point on a path
  48885. */
  48886. var PathCursor = /** @class */ (function () {
  48887. /**
  48888. * Initializes the path cursor
  48889. * @param path The path to track
  48890. */
  48891. function PathCursor(path) {
  48892. this.path = path;
  48893. /**
  48894. * Stores path cursor callbacks for when an onchange event is triggered
  48895. */
  48896. this._onchange = new Array();
  48897. /**
  48898. * The value of the path cursor
  48899. */
  48900. this.value = 0;
  48901. /**
  48902. * The animation array of the path cursor
  48903. */
  48904. this.animations = new Array();
  48905. }
  48906. /**
  48907. * Gets the cursor point on the path
  48908. * @returns A point on the path cursor at the cursor location
  48909. */
  48910. PathCursor.prototype.getPoint = function () {
  48911. var point = this.path.getPointAtLengthPosition(this.value);
  48912. return new BABYLON.Vector3(point.x, 0, point.y);
  48913. };
  48914. /**
  48915. * Moves the cursor ahead by the step amount
  48916. * @param step The amount to move the cursor forward
  48917. * @returns This path cursor
  48918. */
  48919. PathCursor.prototype.moveAhead = function (step) {
  48920. if (step === void 0) { step = 0.002; }
  48921. this.move(step);
  48922. return this;
  48923. };
  48924. /**
  48925. * Moves the cursor behind by the step amount
  48926. * @param step The amount to move the cursor back
  48927. * @returns This path cursor
  48928. */
  48929. PathCursor.prototype.moveBack = function (step) {
  48930. if (step === void 0) { step = 0.002; }
  48931. this.move(-step);
  48932. return this;
  48933. };
  48934. /**
  48935. * Moves the cursor by the step amount
  48936. * If the step amount is greater than one, an exception is thrown
  48937. * @param step The amount to move the cursor
  48938. * @returns This path cursor
  48939. */
  48940. PathCursor.prototype.move = function (step) {
  48941. if (Math.abs(step) > 1) {
  48942. throw "step size should be less than 1.";
  48943. }
  48944. this.value += step;
  48945. this.ensureLimits();
  48946. this.raiseOnChange();
  48947. return this;
  48948. };
  48949. /**
  48950. * Ensures that the value is limited between zero and one
  48951. * @returns This path cursor
  48952. */
  48953. PathCursor.prototype.ensureLimits = function () {
  48954. while (this.value > 1) {
  48955. this.value -= 1;
  48956. }
  48957. while (this.value < 0) {
  48958. this.value += 1;
  48959. }
  48960. return this;
  48961. };
  48962. /**
  48963. * Runs onchange callbacks on change (used by the animation engine)
  48964. * @returns This path cursor
  48965. */
  48966. PathCursor.prototype.raiseOnChange = function () {
  48967. var _this = this;
  48968. this._onchange.forEach(function (f) { return f(_this); });
  48969. return this;
  48970. };
  48971. /**
  48972. * Executes a function on change
  48973. * @param f A path cursor onchange callback
  48974. * @returns This path cursor
  48975. */
  48976. PathCursor.prototype.onchange = function (f) {
  48977. this._onchange.push(f);
  48978. return this;
  48979. };
  48980. return PathCursor;
  48981. }());
  48982. BABYLON.PathCursor = PathCursor;
  48983. /**
  48984. * Enum for the animation key frame interpolation type
  48985. */
  48986. var AnimationKeyInterpolation;
  48987. (function (AnimationKeyInterpolation) {
  48988. /**
  48989. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  48990. */
  48991. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  48992. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  48993. /**
  48994. * Class used to store any kind of animation
  48995. */
  48996. var Animation = /** @class */ (function () {
  48997. /**
  48998. * Initializes the animation
  48999. * @param name Name of the animation
  49000. * @param targetProperty Property to animate
  49001. * @param framePerSecond The frames per second of the animation
  49002. * @param dataType The data type of the animation
  49003. * @param loopMode The loop mode of the animation
  49004. * @param enableBlendings Specifies if blending should be enabled
  49005. */
  49006. function Animation(
  49007. /**Name of the animation */
  49008. name,
  49009. /**Property to animate */
  49010. targetProperty,
  49011. /**The frames per second of the animation */
  49012. framePerSecond,
  49013. /**The data type of the animation */
  49014. dataType,
  49015. /**The loop mode of the animation */
  49016. loopMode,
  49017. /**Specifies if blending should be enabled */
  49018. enableBlending) {
  49019. this.name = name;
  49020. this.targetProperty = targetProperty;
  49021. this.framePerSecond = framePerSecond;
  49022. this.dataType = dataType;
  49023. this.loopMode = loopMode;
  49024. this.enableBlending = enableBlending;
  49025. /**
  49026. * @hidden Internal use only
  49027. */
  49028. this._runtimeAnimations = new Array();
  49029. /**
  49030. * The set of event that will be linked to this animation
  49031. */
  49032. this._events = new Array();
  49033. /**
  49034. * Stores the blending speed of the animation
  49035. */
  49036. this.blendingSpeed = 0.01;
  49037. /**
  49038. * Stores the animation ranges for the animation
  49039. */
  49040. this._ranges = {};
  49041. this.targetPropertyPath = targetProperty.split(".");
  49042. this.dataType = dataType;
  49043. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49044. }
  49045. /**
  49046. * @hidden Internal use
  49047. */
  49048. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49049. var dataType = undefined;
  49050. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49051. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49052. }
  49053. else if (from instanceof BABYLON.Quaternion) {
  49054. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49055. }
  49056. else if (from instanceof BABYLON.Vector3) {
  49057. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49058. }
  49059. else if (from instanceof BABYLON.Vector2) {
  49060. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49061. }
  49062. else if (from instanceof BABYLON.Color3) {
  49063. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49064. }
  49065. else if (from instanceof BABYLON.Size) {
  49066. dataType = Animation.ANIMATIONTYPE_SIZE;
  49067. }
  49068. if (dataType == undefined) {
  49069. return null;
  49070. }
  49071. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49072. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49073. animation.setKeys(keys);
  49074. if (easingFunction !== undefined) {
  49075. animation.setEasingFunction(easingFunction);
  49076. }
  49077. return animation;
  49078. };
  49079. /**
  49080. * Sets up an animation
  49081. * @param property The property to animate
  49082. * @param animationType The animation type to apply
  49083. * @param framePerSecond The frames per second of the animation
  49084. * @param easingFunction The easing function used in the animation
  49085. * @returns The created animation
  49086. */
  49087. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49088. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49089. animation.setEasingFunction(easingFunction);
  49090. return animation;
  49091. };
  49092. /**
  49093. * Create and start an animation on a node
  49094. * @param name defines the name of the global animation that will be run on all nodes
  49095. * @param node defines the root node where the animation will take place
  49096. * @param targetProperty defines property to animate
  49097. * @param framePerSecond defines the number of frame per second yo use
  49098. * @param totalFrame defines the number of frames in total
  49099. * @param from defines the initial value
  49100. * @param to defines the final value
  49101. * @param loopMode defines which loop mode you want to use (off by default)
  49102. * @param easingFunction defines the easing function to use (linear by default)
  49103. * @param onAnimationEnd defines the callback to call when animation end
  49104. * @returns the animatable created for this animation
  49105. */
  49106. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49107. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49108. if (!animation) {
  49109. return null;
  49110. }
  49111. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49112. };
  49113. /**
  49114. * Create and start an animation on a node and its descendants
  49115. * @param name defines the name of the global animation that will be run on all nodes
  49116. * @param node defines the root node where the animation will take place
  49117. * @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
  49118. * @param targetProperty defines property to animate
  49119. * @param framePerSecond defines the number of frame per second to use
  49120. * @param totalFrame defines the number of frames in total
  49121. * @param from defines the initial value
  49122. * @param to defines the final value
  49123. * @param loopMode defines which loop mode you want to use (off by default)
  49124. * @param easingFunction defines the easing function to use (linear by default)
  49125. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49126. * @returns the list of animatables created for all nodes
  49127. * @example https://www.babylonjs-playground.com/#MH0VLI
  49128. */
  49129. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49130. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49131. if (!animation) {
  49132. return null;
  49133. }
  49134. var scene = node.getScene();
  49135. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49136. };
  49137. /**
  49138. * Creates a new animation, merges it with the existing animations and starts it
  49139. * @param name Name of the animation
  49140. * @param node Node which contains the scene that begins the animations
  49141. * @param targetProperty Specifies which property to animate
  49142. * @param framePerSecond The frames per second of the animation
  49143. * @param totalFrame The total number of frames
  49144. * @param from The frame at the beginning of the animation
  49145. * @param to The frame at the end of the animation
  49146. * @param loopMode Specifies the loop mode of the animation
  49147. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49148. * @param onAnimationEnd Callback to run once the animation is complete
  49149. * @returns Nullable animation
  49150. */
  49151. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49152. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49153. if (!animation) {
  49154. return null;
  49155. }
  49156. node.animations.push(animation);
  49157. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49158. };
  49159. /**
  49160. * Transition property of an host to the target Value
  49161. * @param property The property to transition
  49162. * @param targetValue The target Value of the property
  49163. * @param host The object where the property to animate belongs
  49164. * @param scene Scene used to run the animation
  49165. * @param frameRate Framerate (in frame/s) to use
  49166. * @param transition The transition type we want to use
  49167. * @param duration The duration of the animation, in milliseconds
  49168. * @param onAnimationEnd Callback trigger at the end of the animation
  49169. * @returns Nullable animation
  49170. */
  49171. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49172. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49173. if (duration <= 0) {
  49174. host[property] = targetValue;
  49175. if (onAnimationEnd) {
  49176. onAnimationEnd();
  49177. }
  49178. return null;
  49179. }
  49180. var endFrame = frameRate * (duration / 1000);
  49181. transition.setKeys([{
  49182. frame: 0,
  49183. value: host[property].clone ? host[property].clone() : host[property]
  49184. },
  49185. {
  49186. frame: endFrame,
  49187. value: targetValue
  49188. }]);
  49189. if (!host.animations) {
  49190. host.animations = [];
  49191. }
  49192. host.animations.push(transition);
  49193. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49194. animation.onAnimationEnd = onAnimationEnd;
  49195. return animation;
  49196. };
  49197. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49198. /**
  49199. * Return the array of runtime animations currently using this animation
  49200. */
  49201. get: function () {
  49202. return this._runtimeAnimations;
  49203. },
  49204. enumerable: true,
  49205. configurable: true
  49206. });
  49207. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49208. /**
  49209. * Specifies if any of the runtime animations are currently running
  49210. */
  49211. get: function () {
  49212. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49213. var runtimeAnimation = _a[_i];
  49214. if (!runtimeAnimation.isStopped) {
  49215. return true;
  49216. }
  49217. }
  49218. return false;
  49219. },
  49220. enumerable: true,
  49221. configurable: true
  49222. });
  49223. // Methods
  49224. /**
  49225. * Converts the animation to a string
  49226. * @param fullDetails support for multiple levels of logging within scene loading
  49227. * @returns String form of the animation
  49228. */
  49229. Animation.prototype.toString = function (fullDetails) {
  49230. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49231. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49232. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49233. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49234. if (fullDetails) {
  49235. ret += ", Ranges: {";
  49236. var first = true;
  49237. for (var name in this._ranges) {
  49238. if (first) {
  49239. ret += ", ";
  49240. first = false;
  49241. }
  49242. ret += name;
  49243. }
  49244. ret += "}";
  49245. }
  49246. return ret;
  49247. };
  49248. /**
  49249. * Add an event to this animation
  49250. * @param event Event to add
  49251. */
  49252. Animation.prototype.addEvent = function (event) {
  49253. this._events.push(event);
  49254. };
  49255. /**
  49256. * Remove all events found at the given frame
  49257. * @param frame The frame to remove events from
  49258. */
  49259. Animation.prototype.removeEvents = function (frame) {
  49260. for (var index = 0; index < this._events.length; index++) {
  49261. if (this._events[index].frame === frame) {
  49262. this._events.splice(index, 1);
  49263. index--;
  49264. }
  49265. }
  49266. };
  49267. /**
  49268. * Retrieves all the events from the animation
  49269. * @returns Events from the animation
  49270. */
  49271. Animation.prototype.getEvents = function () {
  49272. return this._events;
  49273. };
  49274. /**
  49275. * Creates an animation range
  49276. * @param name Name of the animation range
  49277. * @param from Starting frame of the animation range
  49278. * @param to Ending frame of the animation
  49279. */
  49280. Animation.prototype.createRange = function (name, from, to) {
  49281. // check name not already in use; could happen for bones after serialized
  49282. if (!this._ranges[name]) {
  49283. this._ranges[name] = new AnimationRange(name, from, to);
  49284. }
  49285. };
  49286. /**
  49287. * Deletes an animation range by name
  49288. * @param name Name of the animation range to delete
  49289. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49290. */
  49291. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49292. if (deleteFrames === void 0) { deleteFrames = true; }
  49293. var range = this._ranges[name];
  49294. if (!range) {
  49295. return;
  49296. }
  49297. if (deleteFrames) {
  49298. var from = range.from;
  49299. var to = range.to;
  49300. // this loop MUST go high to low for multiple splices to work
  49301. for (var key = this._keys.length - 1; key >= 0; key--) {
  49302. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49303. this._keys.splice(key, 1);
  49304. }
  49305. }
  49306. }
  49307. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49308. };
  49309. /**
  49310. * Gets the animation range by name, or null if not defined
  49311. * @param name Name of the animation range
  49312. * @returns Nullable animation range
  49313. */
  49314. Animation.prototype.getRange = function (name) {
  49315. return this._ranges[name];
  49316. };
  49317. /**
  49318. * Gets the key frames from the animation
  49319. * @returns The key frames of the animation
  49320. */
  49321. Animation.prototype.getKeys = function () {
  49322. return this._keys;
  49323. };
  49324. /**
  49325. * Gets the highest frame rate of the animation
  49326. * @returns Highest frame rate of the animation
  49327. */
  49328. Animation.prototype.getHighestFrame = function () {
  49329. var ret = 0;
  49330. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49331. if (ret < this._keys[key].frame) {
  49332. ret = this._keys[key].frame;
  49333. }
  49334. }
  49335. return ret;
  49336. };
  49337. /**
  49338. * Gets the easing function of the animation
  49339. * @returns Easing function of the animation
  49340. */
  49341. Animation.prototype.getEasingFunction = function () {
  49342. return this._easingFunction;
  49343. };
  49344. /**
  49345. * Sets the easing function of the animation
  49346. * @param easingFunction A custom mathematical formula for animation
  49347. */
  49348. Animation.prototype.setEasingFunction = function (easingFunction) {
  49349. this._easingFunction = easingFunction;
  49350. };
  49351. /**
  49352. * Interpolates a scalar linearly
  49353. * @param startValue Start value of the animation curve
  49354. * @param endValue End value of the animation curve
  49355. * @param gradient Scalar amount to interpolate
  49356. * @returns Interpolated scalar value
  49357. */
  49358. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49359. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49360. };
  49361. /**
  49362. * Interpolates a scalar cubically
  49363. * @param startValue Start value of the animation curve
  49364. * @param outTangent End tangent of the animation
  49365. * @param endValue End value of the animation curve
  49366. * @param inTangent Start tangent of the animation curve
  49367. * @param gradient Scalar amount to interpolate
  49368. * @returns Interpolated scalar value
  49369. */
  49370. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49371. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49372. };
  49373. /**
  49374. * Interpolates a quaternion using a spherical linear interpolation
  49375. * @param startValue Start value of the animation curve
  49376. * @param endValue End value of the animation curve
  49377. * @param gradient Scalar amount to interpolate
  49378. * @returns Interpolated quaternion value
  49379. */
  49380. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49381. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49382. };
  49383. /**
  49384. * Interpolates a quaternion cubically
  49385. * @param startValue Start value of the animation curve
  49386. * @param outTangent End tangent of the animation curve
  49387. * @param endValue End value of the animation curve
  49388. * @param inTangent Start tangent of the animation curve
  49389. * @param gradient Scalar amount to interpolate
  49390. * @returns Interpolated quaternion value
  49391. */
  49392. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49393. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49394. };
  49395. /**
  49396. * Interpolates a Vector3 linearl
  49397. * @param startValue Start value of the animation curve
  49398. * @param endValue End value of the animation curve
  49399. * @param gradient Scalar amount to interpolate
  49400. * @returns Interpolated scalar value
  49401. */
  49402. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49403. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49404. };
  49405. /**
  49406. * Interpolates a Vector3 cubically
  49407. * @param startValue Start value of the animation curve
  49408. * @param outTangent End tangent of the animation
  49409. * @param endValue End value of the animation curve
  49410. * @param inTangent Start tangent of the animation curve
  49411. * @param gradient Scalar amount to interpolate
  49412. * @returns InterpolatedVector3 value
  49413. */
  49414. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49415. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49416. };
  49417. /**
  49418. * Interpolates a Vector2 linearly
  49419. * @param startValue Start value of the animation curve
  49420. * @param endValue End value of the animation curve
  49421. * @param gradient Scalar amount to interpolate
  49422. * @returns Interpolated Vector2 value
  49423. */
  49424. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49425. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49426. };
  49427. /**
  49428. * Interpolates a Vector2 cubically
  49429. * @param startValue Start value of the animation curve
  49430. * @param outTangent End tangent of the animation
  49431. * @param endValue End value of the animation curve
  49432. * @param inTangent Start tangent of the animation curve
  49433. * @param gradient Scalar amount to interpolate
  49434. * @returns Interpolated Vector2 value
  49435. */
  49436. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49437. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49438. };
  49439. /**
  49440. * Interpolates a size linearly
  49441. * @param startValue Start value of the animation curve
  49442. * @param endValue End value of the animation curve
  49443. * @param gradient Scalar amount to interpolate
  49444. * @returns Interpolated Size value
  49445. */
  49446. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49447. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49448. };
  49449. /**
  49450. * Interpolates a Color3 linearly
  49451. * @param startValue Start value of the animation curve
  49452. * @param endValue End value of the animation curve
  49453. * @param gradient Scalar amount to interpolate
  49454. * @returns Interpolated Color3 value
  49455. */
  49456. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49457. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49458. };
  49459. /**
  49460. * @hidden Internal use only
  49461. */
  49462. Animation.prototype._getKeyValue = function (value) {
  49463. if (typeof value === "function") {
  49464. return value();
  49465. }
  49466. return value;
  49467. };
  49468. /**
  49469. * @hidden Internal use only
  49470. */
  49471. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49472. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49473. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49474. }
  49475. var keys = this.getKeys();
  49476. // Try to get a hash to find the right key
  49477. 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));
  49478. if (keys[startKeyIndex].frame >= currentFrame) {
  49479. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49480. startKeyIndex--;
  49481. }
  49482. }
  49483. for (var key = startKeyIndex; key < keys.length; key++) {
  49484. var endKey = keys[key + 1];
  49485. if (endKey.frame >= currentFrame) {
  49486. var startKey = keys[key];
  49487. var startValue = this._getKeyValue(startKey.value);
  49488. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49489. return startValue;
  49490. }
  49491. var endValue = this._getKeyValue(endKey.value);
  49492. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49493. var frameDelta = endKey.frame - startKey.frame;
  49494. // gradient : percent of currentFrame between the frame inf and the frame sup
  49495. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49496. // check for easingFunction and correction of gradient
  49497. var easingFunction = this.getEasingFunction();
  49498. if (easingFunction != null) {
  49499. gradient = easingFunction.ease(gradient);
  49500. }
  49501. switch (this.dataType) {
  49502. // Float
  49503. case Animation.ANIMATIONTYPE_FLOAT:
  49504. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49505. switch (loopMode) {
  49506. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49507. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49508. return floatValue;
  49509. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49510. return offsetValue * repeatCount + floatValue;
  49511. }
  49512. break;
  49513. // Quaternion
  49514. case Animation.ANIMATIONTYPE_QUATERNION:
  49515. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49516. switch (loopMode) {
  49517. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49518. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49519. return quatValue;
  49520. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49521. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49522. }
  49523. return quatValue;
  49524. // Vector3
  49525. case Animation.ANIMATIONTYPE_VECTOR3:
  49526. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49527. switch (loopMode) {
  49528. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49529. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49530. return vec3Value;
  49531. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49532. return vec3Value.add(offsetValue.scale(repeatCount));
  49533. }
  49534. // Vector2
  49535. case Animation.ANIMATIONTYPE_VECTOR2:
  49536. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49537. switch (loopMode) {
  49538. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49539. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49540. return vec2Value;
  49541. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49542. return vec2Value.add(offsetValue.scale(repeatCount));
  49543. }
  49544. // Size
  49545. case Animation.ANIMATIONTYPE_SIZE:
  49546. switch (loopMode) {
  49547. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49548. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49549. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49550. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49551. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49552. }
  49553. // Color3
  49554. case Animation.ANIMATIONTYPE_COLOR3:
  49555. switch (loopMode) {
  49556. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49557. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49558. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49559. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49560. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49561. }
  49562. // Matrix
  49563. case Animation.ANIMATIONTYPE_MATRIX:
  49564. switch (loopMode) {
  49565. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49566. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49567. if (Animation.AllowMatricesInterpolation) {
  49568. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49569. }
  49570. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49571. return startValue;
  49572. }
  49573. default:
  49574. break;
  49575. }
  49576. break;
  49577. }
  49578. }
  49579. return this._getKeyValue(keys[keys.length - 1].value);
  49580. };
  49581. /**
  49582. * Defines the function to use to interpolate matrices
  49583. * @param startValue defines the start matrix
  49584. * @param endValue defines the end matrix
  49585. * @param gradient defines the gradient between both matrices
  49586. * @param result defines an optional target matrix where to store the interpolation
  49587. * @returns the interpolated matrix
  49588. */
  49589. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49590. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49591. if (result) {
  49592. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49593. return result;
  49594. }
  49595. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49596. }
  49597. if (result) {
  49598. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49599. return result;
  49600. }
  49601. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49602. };
  49603. /**
  49604. * Makes a copy of the animation
  49605. * @returns Cloned animation
  49606. */
  49607. Animation.prototype.clone = function () {
  49608. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49609. clone.enableBlending = this.enableBlending;
  49610. clone.blendingSpeed = this.blendingSpeed;
  49611. if (this._keys) {
  49612. clone.setKeys(this._keys);
  49613. }
  49614. if (this._ranges) {
  49615. clone._ranges = {};
  49616. for (var name in this._ranges) {
  49617. var range = this._ranges[name];
  49618. if (!range) {
  49619. continue;
  49620. }
  49621. clone._ranges[name] = range.clone();
  49622. }
  49623. }
  49624. return clone;
  49625. };
  49626. /**
  49627. * Sets the key frames of the animation
  49628. * @param values The animation key frames to set
  49629. */
  49630. Animation.prototype.setKeys = function (values) {
  49631. this._keys = values.slice(0);
  49632. };
  49633. /**
  49634. * Serializes the animation to an object
  49635. * @returns Serialized object
  49636. */
  49637. Animation.prototype.serialize = function () {
  49638. var serializationObject = {};
  49639. serializationObject.name = this.name;
  49640. serializationObject.property = this.targetProperty;
  49641. serializationObject.framePerSecond = this.framePerSecond;
  49642. serializationObject.dataType = this.dataType;
  49643. serializationObject.loopBehavior = this.loopMode;
  49644. serializationObject.enableBlending = this.enableBlending;
  49645. serializationObject.blendingSpeed = this.blendingSpeed;
  49646. var dataType = this.dataType;
  49647. serializationObject.keys = [];
  49648. var keys = this.getKeys();
  49649. for (var index = 0; index < keys.length; index++) {
  49650. var animationKey = keys[index];
  49651. var key = {};
  49652. key.frame = animationKey.frame;
  49653. switch (dataType) {
  49654. case Animation.ANIMATIONTYPE_FLOAT:
  49655. key.values = [animationKey.value];
  49656. break;
  49657. case Animation.ANIMATIONTYPE_QUATERNION:
  49658. case Animation.ANIMATIONTYPE_MATRIX:
  49659. case Animation.ANIMATIONTYPE_VECTOR3:
  49660. case Animation.ANIMATIONTYPE_COLOR3:
  49661. key.values = animationKey.value.asArray();
  49662. break;
  49663. }
  49664. serializationObject.keys.push(key);
  49665. }
  49666. serializationObject.ranges = [];
  49667. for (var name in this._ranges) {
  49668. var source = this._ranges[name];
  49669. if (!source) {
  49670. continue;
  49671. }
  49672. var range = {};
  49673. range.name = name;
  49674. range.from = source.from;
  49675. range.to = source.to;
  49676. serializationObject.ranges.push(range);
  49677. }
  49678. return serializationObject;
  49679. };
  49680. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49681. /**
  49682. * Get the float animation type
  49683. */
  49684. get: function () {
  49685. return Animation._ANIMATIONTYPE_FLOAT;
  49686. },
  49687. enumerable: true,
  49688. configurable: true
  49689. });
  49690. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49691. /**
  49692. * Get the Vector3 animation type
  49693. */
  49694. get: function () {
  49695. return Animation._ANIMATIONTYPE_VECTOR3;
  49696. },
  49697. enumerable: true,
  49698. configurable: true
  49699. });
  49700. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49701. /**
  49702. * Get the Vectpr2 animation type
  49703. */
  49704. get: function () {
  49705. return Animation._ANIMATIONTYPE_VECTOR2;
  49706. },
  49707. enumerable: true,
  49708. configurable: true
  49709. });
  49710. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49711. /**
  49712. * Get the Size animation type
  49713. */
  49714. get: function () {
  49715. return Animation._ANIMATIONTYPE_SIZE;
  49716. },
  49717. enumerable: true,
  49718. configurable: true
  49719. });
  49720. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49721. /**
  49722. * Get the Quaternion animation type
  49723. */
  49724. get: function () {
  49725. return Animation._ANIMATIONTYPE_QUATERNION;
  49726. },
  49727. enumerable: true,
  49728. configurable: true
  49729. });
  49730. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49731. /**
  49732. * Get the Matrix animation type
  49733. */
  49734. get: function () {
  49735. return Animation._ANIMATIONTYPE_MATRIX;
  49736. },
  49737. enumerable: true,
  49738. configurable: true
  49739. });
  49740. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49741. /**
  49742. * Get the Color3 animation type
  49743. */
  49744. get: function () {
  49745. return Animation._ANIMATIONTYPE_COLOR3;
  49746. },
  49747. enumerable: true,
  49748. configurable: true
  49749. });
  49750. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49751. /**
  49752. * Get the Relative Loop Mode
  49753. */
  49754. get: function () {
  49755. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49756. },
  49757. enumerable: true,
  49758. configurable: true
  49759. });
  49760. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49761. /**
  49762. * Get the Cycle Loop Mode
  49763. */
  49764. get: function () {
  49765. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49766. },
  49767. enumerable: true,
  49768. configurable: true
  49769. });
  49770. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49771. /**
  49772. * Get the Constant Loop Mode
  49773. */
  49774. get: function () {
  49775. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49776. },
  49777. enumerable: true,
  49778. configurable: true
  49779. });
  49780. /** @hidden */
  49781. Animation._UniversalLerp = function (left, right, amount) {
  49782. var constructor = left.constructor;
  49783. if (constructor.Lerp) { // Lerp supported
  49784. return constructor.Lerp(left, right, amount);
  49785. }
  49786. else if (constructor.Slerp) { // Slerp supported
  49787. return constructor.Slerp(left, right, amount);
  49788. }
  49789. else if (left.toFixed) { // Number
  49790. return left * (1.0 - amount) + amount * right;
  49791. }
  49792. else { // Blending not supported
  49793. return right;
  49794. }
  49795. };
  49796. /**
  49797. * Parses an animation object and creates an animation
  49798. * @param parsedAnimation Parsed animation object
  49799. * @returns Animation object
  49800. */
  49801. Animation.Parse = function (parsedAnimation) {
  49802. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49803. var dataType = parsedAnimation.dataType;
  49804. var keys = [];
  49805. var data;
  49806. var index;
  49807. if (parsedAnimation.enableBlending) {
  49808. animation.enableBlending = parsedAnimation.enableBlending;
  49809. }
  49810. if (parsedAnimation.blendingSpeed) {
  49811. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49812. }
  49813. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49814. var key = parsedAnimation.keys[index];
  49815. var inTangent;
  49816. var outTangent;
  49817. switch (dataType) {
  49818. case Animation.ANIMATIONTYPE_FLOAT:
  49819. data = key.values[0];
  49820. if (key.values.length >= 1) {
  49821. inTangent = key.values[1];
  49822. }
  49823. if (key.values.length >= 2) {
  49824. outTangent = key.values[2];
  49825. }
  49826. break;
  49827. case Animation.ANIMATIONTYPE_QUATERNION:
  49828. data = BABYLON.Quaternion.FromArray(key.values);
  49829. if (key.values.length >= 8) {
  49830. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49831. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49832. inTangent = _inTangent;
  49833. }
  49834. }
  49835. if (key.values.length >= 12) {
  49836. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49837. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49838. outTangent = _outTangent;
  49839. }
  49840. }
  49841. break;
  49842. case Animation.ANIMATIONTYPE_MATRIX:
  49843. data = BABYLON.Matrix.FromArray(key.values);
  49844. break;
  49845. case Animation.ANIMATIONTYPE_COLOR3:
  49846. data = BABYLON.Color3.FromArray(key.values);
  49847. break;
  49848. case Animation.ANIMATIONTYPE_VECTOR3:
  49849. default:
  49850. data = BABYLON.Vector3.FromArray(key.values);
  49851. break;
  49852. }
  49853. var keyData = {};
  49854. keyData.frame = key.frame;
  49855. keyData.value = data;
  49856. if (inTangent != undefined) {
  49857. keyData.inTangent = inTangent;
  49858. }
  49859. if (outTangent != undefined) {
  49860. keyData.outTangent = outTangent;
  49861. }
  49862. keys.push(keyData);
  49863. }
  49864. animation.setKeys(keys);
  49865. if (parsedAnimation.ranges) {
  49866. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49867. data = parsedAnimation.ranges[index];
  49868. animation.createRange(data.name, data.from, data.to);
  49869. }
  49870. }
  49871. return animation;
  49872. };
  49873. /**
  49874. * Appends the serialized animations from the source animations
  49875. * @param source Source containing the animations
  49876. * @param destination Target to store the animations
  49877. */
  49878. Animation.AppendSerializedAnimations = function (source, destination) {
  49879. if (source.animations) {
  49880. destination.animations = [];
  49881. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49882. var animation = source.animations[animationIndex];
  49883. destination.animations.push(animation.serialize());
  49884. }
  49885. }
  49886. };
  49887. /**
  49888. * Use matrix interpolation instead of using direct key value when animating matrices
  49889. */
  49890. Animation.AllowMatricesInterpolation = false;
  49891. /**
  49892. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49893. */
  49894. Animation.AllowMatrixDecomposeForInterpolation = true;
  49895. // Statics
  49896. /**
  49897. * Float animation type
  49898. */
  49899. Animation._ANIMATIONTYPE_FLOAT = 0;
  49900. /**
  49901. * Vector3 animation type
  49902. */
  49903. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49904. /**
  49905. * Quaternion animation type
  49906. */
  49907. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49908. /**
  49909. * Matrix animation type
  49910. */
  49911. Animation._ANIMATIONTYPE_MATRIX = 3;
  49912. /**
  49913. * Color3 animation type
  49914. */
  49915. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49916. /**
  49917. * Vector2 animation type
  49918. */
  49919. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49920. /**
  49921. * Size animation type
  49922. */
  49923. Animation._ANIMATIONTYPE_SIZE = 6;
  49924. /**
  49925. * Relative Loop Mode
  49926. */
  49927. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49928. /**
  49929. * Cycle Loop Mode
  49930. */
  49931. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49932. /**
  49933. * Constant Loop Mode
  49934. */
  49935. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49936. return Animation;
  49937. }());
  49938. BABYLON.Animation = Animation;
  49939. })(BABYLON || (BABYLON = {}));
  49940. //# sourceMappingURL=babylon.animation.js.map
  49941. var BABYLON;
  49942. (function (BABYLON) {
  49943. /**
  49944. * This class defines the direct association between an animation and a target
  49945. */
  49946. var TargetedAnimation = /** @class */ (function () {
  49947. function TargetedAnimation() {
  49948. }
  49949. return TargetedAnimation;
  49950. }());
  49951. BABYLON.TargetedAnimation = TargetedAnimation;
  49952. /**
  49953. * Use this class to create coordinated animations on multiple targets
  49954. */
  49955. var AnimationGroup = /** @class */ (function () {
  49956. function AnimationGroup(name, scene) {
  49957. if (scene === void 0) { scene = null; }
  49958. this.name = name;
  49959. this._targetedAnimations = new Array();
  49960. this._animatables = new Array();
  49961. this._from = Number.MAX_VALUE;
  49962. this._to = -Number.MAX_VALUE;
  49963. this._speedRatio = 1;
  49964. this.onAnimationEndObservable = new BABYLON.Observable();
  49965. /**
  49966. * This observable will notify when all animations have ended.
  49967. */
  49968. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  49969. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49970. this._scene.animationGroups.push(this);
  49971. }
  49972. Object.defineProperty(AnimationGroup.prototype, "from", {
  49973. /**
  49974. * Gets the first frame
  49975. */
  49976. get: function () {
  49977. return this._from;
  49978. },
  49979. enumerable: true,
  49980. configurable: true
  49981. });
  49982. Object.defineProperty(AnimationGroup.prototype, "to", {
  49983. /**
  49984. * Gets the last frame
  49985. */
  49986. get: function () {
  49987. return this._to;
  49988. },
  49989. enumerable: true,
  49990. configurable: true
  49991. });
  49992. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49993. /**
  49994. * Define if the animations are started
  49995. */
  49996. get: function () {
  49997. return this._isStarted;
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50003. /**
  50004. * Gets or sets the speed ratio to use for all animations
  50005. */
  50006. get: function () {
  50007. return this._speedRatio;
  50008. },
  50009. /**
  50010. * Gets or sets the speed ratio to use for all animations
  50011. */
  50012. set: function (value) {
  50013. if (this._speedRatio === value) {
  50014. return;
  50015. }
  50016. this._speedRatio = value;
  50017. for (var index = 0; index < this._animatables.length; index++) {
  50018. var animatable = this._animatables[index];
  50019. animatable.speedRatio = this._speedRatio;
  50020. }
  50021. },
  50022. enumerable: true,
  50023. configurable: true
  50024. });
  50025. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50026. /**
  50027. * Gets the targeted animations for this animation group
  50028. */
  50029. get: function () {
  50030. return this._targetedAnimations;
  50031. },
  50032. enumerable: true,
  50033. configurable: true
  50034. });
  50035. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50036. /**
  50037. * returning the list of animatables controlled by this animation group.
  50038. */
  50039. get: function () {
  50040. return this._animatables;
  50041. },
  50042. enumerable: true,
  50043. configurable: true
  50044. });
  50045. /**
  50046. * Add an animation (with its target) in the group
  50047. * @param animation defines the animation we want to add
  50048. * @param target defines the target of the animation
  50049. * @returns the {BABYLON.TargetedAnimation} object
  50050. */
  50051. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50052. var targetedAnimation = {
  50053. animation: animation,
  50054. target: target
  50055. };
  50056. var keys = animation.getKeys();
  50057. if (this._from > keys[0].frame) {
  50058. this._from = keys[0].frame;
  50059. }
  50060. if (this._to < keys[keys.length - 1].frame) {
  50061. this._to = keys[keys.length - 1].frame;
  50062. }
  50063. this._targetedAnimations.push(targetedAnimation);
  50064. return targetedAnimation;
  50065. };
  50066. /**
  50067. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50068. * It can add constant keys at begin or end
  50069. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50070. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50071. */
  50072. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50073. if (beginFrame === void 0) { beginFrame = null; }
  50074. if (endFrame === void 0) { endFrame = null; }
  50075. if (beginFrame == null)
  50076. beginFrame = this._from;
  50077. if (endFrame == null)
  50078. endFrame = this._to;
  50079. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50080. var targetedAnimation = this._targetedAnimations[index];
  50081. var keys = targetedAnimation.animation.getKeys();
  50082. var startKey = keys[0];
  50083. var endKey = keys[keys.length - 1];
  50084. if (startKey.frame > beginFrame) {
  50085. var newKey = {
  50086. frame: beginFrame,
  50087. value: startKey.value,
  50088. inTangent: startKey.inTangent,
  50089. outTangent: startKey.outTangent,
  50090. interpolation: startKey.interpolation
  50091. };
  50092. keys.splice(0, 0, newKey);
  50093. }
  50094. if (endKey.frame < endFrame) {
  50095. var newKey = {
  50096. frame: endFrame,
  50097. value: endKey.value,
  50098. inTangent: endKey.outTangent,
  50099. outTangent: endKey.outTangent,
  50100. interpolation: endKey.interpolation
  50101. };
  50102. keys.push(newKey);
  50103. }
  50104. }
  50105. this._from = beginFrame;
  50106. this._to = endFrame;
  50107. return this;
  50108. };
  50109. /**
  50110. * Start all animations on given targets
  50111. * @param loop defines if animations must loop
  50112. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50113. * @param from defines the from key (optional)
  50114. * @param to defines the to key (optional)
  50115. * @returns the current animation group
  50116. */
  50117. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50118. var _this = this;
  50119. if (loop === void 0) { loop = false; }
  50120. if (speedRatio === void 0) { speedRatio = 1; }
  50121. if (this._isStarted || this._targetedAnimations.length === 0) {
  50122. return this;
  50123. }
  50124. var _loop_1 = function (targetedAnimation) {
  50125. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50126. animatable.onAnimationEnd = function () {
  50127. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50128. _this._checkAnimationGroupEnded(animatable);
  50129. };
  50130. this_1._animatables.push(animatable);
  50131. };
  50132. var this_1 = this;
  50133. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50134. var targetedAnimation = _a[_i];
  50135. _loop_1(targetedAnimation);
  50136. }
  50137. this._speedRatio = speedRatio;
  50138. this._isStarted = true;
  50139. return this;
  50140. };
  50141. /**
  50142. * Pause all animations
  50143. */
  50144. AnimationGroup.prototype.pause = function () {
  50145. if (!this._isStarted) {
  50146. return this;
  50147. }
  50148. for (var index = 0; index < this._animatables.length; index++) {
  50149. var animatable = this._animatables[index];
  50150. animatable.pause();
  50151. }
  50152. return this;
  50153. };
  50154. /**
  50155. * Play all animations to initial state
  50156. * This function will start() the animations if they were not started or will restart() them if they were paused
  50157. * @param loop defines if animations must loop
  50158. */
  50159. AnimationGroup.prototype.play = function (loop) {
  50160. // only if all animatables are ready and exist
  50161. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50162. if (loop !== undefined) {
  50163. for (var index = 0; index < this._animatables.length; index++) {
  50164. var animatable = this._animatables[index];
  50165. animatable.loopAnimation = loop;
  50166. }
  50167. }
  50168. this.restart();
  50169. }
  50170. else {
  50171. this.stop();
  50172. this.start(loop, this._speedRatio);
  50173. }
  50174. return this;
  50175. };
  50176. /**
  50177. * Reset all animations to initial state
  50178. */
  50179. AnimationGroup.prototype.reset = function () {
  50180. if (!this._isStarted) {
  50181. return this;
  50182. }
  50183. for (var index = 0; index < this._animatables.length; index++) {
  50184. var animatable = this._animatables[index];
  50185. animatable.reset();
  50186. }
  50187. return this;
  50188. };
  50189. /**
  50190. * Restart animations from key 0
  50191. */
  50192. AnimationGroup.prototype.restart = function () {
  50193. if (!this._isStarted) {
  50194. return this;
  50195. }
  50196. for (var index = 0; index < this._animatables.length; index++) {
  50197. var animatable = this._animatables[index];
  50198. animatable.restart();
  50199. }
  50200. return this;
  50201. };
  50202. /**
  50203. * Stop all animations
  50204. */
  50205. AnimationGroup.prototype.stop = function () {
  50206. if (!this._isStarted) {
  50207. return this;
  50208. }
  50209. var list = this._animatables.slice();
  50210. for (var index = 0; index < list.length; index++) {
  50211. list[index].stop();
  50212. }
  50213. this._isStarted = false;
  50214. return this;
  50215. };
  50216. /**
  50217. * Set animation weight for all animatables
  50218. * @param weight defines the weight to use
  50219. * @return the animationGroup
  50220. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50221. */
  50222. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50223. for (var index = 0; index < this._animatables.length; index++) {
  50224. var animatable = this._animatables[index];
  50225. animatable.weight = weight;
  50226. }
  50227. return this;
  50228. };
  50229. /**
  50230. * Synchronize and normalize all animatables with a source animatable
  50231. * @param root defines the root animatable to synchronize with
  50232. * @return the animationGroup
  50233. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50234. */
  50235. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50236. for (var index = 0; index < this._animatables.length; index++) {
  50237. var animatable = this._animatables[index];
  50238. animatable.syncWith(root);
  50239. }
  50240. return this;
  50241. };
  50242. /**
  50243. * Goes to a specific frame in this animation group
  50244. * @param frame the frame number to go to
  50245. * @return the animationGroup
  50246. */
  50247. AnimationGroup.prototype.goToFrame = function (frame) {
  50248. if (!this._isStarted) {
  50249. return this;
  50250. }
  50251. for (var index = 0; index < this._animatables.length; index++) {
  50252. var animatable = this._animatables[index];
  50253. animatable.goToFrame(frame);
  50254. }
  50255. return this;
  50256. };
  50257. /**
  50258. * Dispose all associated resources
  50259. */
  50260. AnimationGroup.prototype.dispose = function () {
  50261. this._targetedAnimations = [];
  50262. this._animatables = [];
  50263. var index = this._scene.animationGroups.indexOf(this);
  50264. if (index > -1) {
  50265. this._scene.animationGroups.splice(index, 1);
  50266. }
  50267. };
  50268. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50269. // animatable should be taken out of the array
  50270. var idx = this._animatables.indexOf(animatable);
  50271. if (idx > -1) {
  50272. this._animatables.splice(idx, 1);
  50273. }
  50274. // all animatables were removed? animation group ended!
  50275. if (this._animatables.length === 0) {
  50276. this._isStarted = false;
  50277. this.onAnimationGroupEndObservable.notifyObservers(this);
  50278. }
  50279. };
  50280. return AnimationGroup;
  50281. }());
  50282. BABYLON.AnimationGroup = AnimationGroup;
  50283. })(BABYLON || (BABYLON = {}));
  50284. //# sourceMappingURL=babylon.animationGroup.js.map
  50285. var BABYLON;
  50286. (function (BABYLON) {
  50287. /**
  50288. * Defines a runtime animation
  50289. */
  50290. var RuntimeAnimation = /** @class */ (function () {
  50291. /**
  50292. * Create a new RuntimeAnimation object
  50293. * @param target defines the target of the animation
  50294. * @param animation defines the source animation object
  50295. * @param scene defines the hosting scene
  50296. * @param host defines the initiating Animatable
  50297. */
  50298. function RuntimeAnimation(target, animation, scene, host) {
  50299. var _this = this;
  50300. this._events = new Array();
  50301. /**
  50302. * The current frame of the runtime animation
  50303. */
  50304. this._currentFrame = 0;
  50305. /**
  50306. * The original value of the runtime animation
  50307. */
  50308. this._originalValue = new Array();
  50309. /**
  50310. * The offsets cache of the runtime animation
  50311. */
  50312. this._offsetsCache = {};
  50313. /**
  50314. * The high limits cache of the runtime animation
  50315. */
  50316. this._highLimitsCache = {};
  50317. /**
  50318. * Specifies if the runtime animation has been stopped
  50319. */
  50320. this._stopped = false;
  50321. /**
  50322. * The blending factor of the runtime animation
  50323. */
  50324. this._blendingFactor = 0;
  50325. /**
  50326. * The target path of the runtime animation
  50327. */
  50328. this._targetPath = "";
  50329. /**
  50330. * The weight of the runtime animation
  50331. */
  50332. this._weight = 1.0;
  50333. /**
  50334. * The ratio offset of the runtime animation
  50335. */
  50336. this._ratioOffset = 0;
  50337. /**
  50338. * The previous delay of the runtime animation
  50339. */
  50340. this._previousDelay = 0;
  50341. /**
  50342. * The previous ratio of the runtime animation
  50343. */
  50344. this._previousRatio = 0;
  50345. this._animation = animation;
  50346. this._target = target;
  50347. this._scene = scene;
  50348. this._host = host;
  50349. animation._runtimeAnimations.push(this);
  50350. // Cloning events locally
  50351. var events = animation.getEvents();
  50352. if (events && events.length > 0) {
  50353. events.forEach(function (e) {
  50354. _this._events.push(e._clone());
  50355. });
  50356. }
  50357. }
  50358. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50359. /**
  50360. * Gets the current frame of the runtime animation
  50361. */
  50362. get: function () {
  50363. return this._currentFrame;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50369. /**
  50370. * Gets the weight of the runtime animation
  50371. */
  50372. get: function () {
  50373. return this._weight;
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50379. /**
  50380. * Gets the current value of the runtime animation
  50381. */
  50382. get: function () {
  50383. return this._currentValue;
  50384. },
  50385. enumerable: true,
  50386. configurable: true
  50387. });
  50388. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50389. /**
  50390. * Gets the target path of the runtime animation
  50391. */
  50392. get: function () {
  50393. return this._targetPath;
  50394. },
  50395. enumerable: true,
  50396. configurable: true
  50397. });
  50398. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50399. /**
  50400. * Gets the actual target of the runtime animation
  50401. */
  50402. get: function () {
  50403. return this._activeTarget;
  50404. },
  50405. enumerable: true,
  50406. configurable: true
  50407. });
  50408. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50409. /**
  50410. * Gets the animation from the runtime animation
  50411. */
  50412. get: function () {
  50413. return this._animation;
  50414. },
  50415. enumerable: true,
  50416. configurable: true
  50417. });
  50418. /**
  50419. * Resets the runtime animation to the beginning
  50420. * @param restoreOriginal defines whether to restore the target property to the original value
  50421. */
  50422. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50423. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50424. if (restoreOriginal) {
  50425. if (this._target instanceof Array) {
  50426. var index = 0;
  50427. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50428. var target = _a[_i];
  50429. if (this._originalValue[index] !== undefined) {
  50430. this._setValue(target, this._originalValue[index], -1);
  50431. }
  50432. index++;
  50433. }
  50434. }
  50435. else {
  50436. if (this._originalValue[0] !== undefined) {
  50437. this._setValue(this._target, this._originalValue[0], -1);
  50438. }
  50439. }
  50440. }
  50441. this._offsetsCache = {};
  50442. this._highLimitsCache = {};
  50443. this._currentFrame = 0;
  50444. this._blendingFactor = 0;
  50445. this._originalValue = new Array();
  50446. // Events
  50447. for (var index = 0; index < this._events.length; index++) {
  50448. this._events[index].isDone = false;
  50449. }
  50450. };
  50451. /**
  50452. * Specifies if the runtime animation is stopped
  50453. * @returns Boolean specifying if the runtime animation is stopped
  50454. */
  50455. RuntimeAnimation.prototype.isStopped = function () {
  50456. return this._stopped;
  50457. };
  50458. /**
  50459. * Disposes of the runtime animation
  50460. */
  50461. RuntimeAnimation.prototype.dispose = function () {
  50462. var index = this._animation.runtimeAnimations.indexOf(this);
  50463. if (index > -1) {
  50464. this._animation.runtimeAnimations.splice(index, 1);
  50465. }
  50466. };
  50467. /**
  50468. * Interpolates the animation from the current frame
  50469. * @param currentFrame The frame to interpolate the animation to
  50470. * @param repeatCount The number of times that the animation should loop
  50471. * @param loopMode The type of looping mode to use
  50472. * @param offsetValue Animation offset value
  50473. * @param highLimitValue The high limit value
  50474. * @returns The interpolated value
  50475. */
  50476. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50477. this._currentFrame = currentFrame;
  50478. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50479. this._workValue = BABYLON.Matrix.Zero();
  50480. }
  50481. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50482. };
  50483. /**
  50484. * Apply the interpolated value to the target
  50485. * @param currentValue defines the value computed by the animation
  50486. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50487. */
  50488. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50489. if (weight === void 0) { weight = 1.0; }
  50490. if (this._target instanceof Array) {
  50491. var index = 0;
  50492. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50493. var target = _a[_i];
  50494. this._setValue(target, currentValue, weight, index);
  50495. index++;
  50496. }
  50497. }
  50498. else {
  50499. this._setValue(this._target, currentValue, weight);
  50500. }
  50501. };
  50502. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50503. if (targetIndex === void 0) { targetIndex = 0; }
  50504. // Set value
  50505. var path;
  50506. var destination;
  50507. var targetPropertyPath = this._animation.targetPropertyPath;
  50508. if (targetPropertyPath.length > 1) {
  50509. var property = target[targetPropertyPath[0]];
  50510. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50511. property = property[targetPropertyPath[index]];
  50512. }
  50513. path = targetPropertyPath[targetPropertyPath.length - 1];
  50514. destination = property;
  50515. }
  50516. else {
  50517. path = targetPropertyPath[0];
  50518. destination = target;
  50519. }
  50520. this._targetPath = path;
  50521. this._activeTarget = destination;
  50522. this._weight = weight;
  50523. if (this._originalValue[targetIndex] === undefined) {
  50524. var originalValue = void 0;
  50525. if (destination.getRestPose && path === "_matrix") { // For bones
  50526. originalValue = destination.getRestPose();
  50527. }
  50528. else {
  50529. originalValue = destination[path];
  50530. }
  50531. if (originalValue && originalValue.clone) {
  50532. this._originalValue[targetIndex] = originalValue.clone();
  50533. }
  50534. else {
  50535. this._originalValue[targetIndex] = originalValue;
  50536. }
  50537. }
  50538. // Blending
  50539. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50540. if (enableBlending && this._blendingFactor <= 1.0) {
  50541. if (!this._originalBlendValue) {
  50542. var originalValue = destination[path];
  50543. if (originalValue.clone) {
  50544. this._originalBlendValue = originalValue.clone();
  50545. }
  50546. else {
  50547. this._originalBlendValue = originalValue;
  50548. }
  50549. }
  50550. if (this._originalBlendValue.m) { // Matrix
  50551. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50552. if (this._currentValue) {
  50553. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50554. }
  50555. else {
  50556. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50557. }
  50558. }
  50559. else {
  50560. if (this._currentValue) {
  50561. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50562. }
  50563. else {
  50564. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50565. }
  50566. }
  50567. }
  50568. else {
  50569. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50570. }
  50571. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50572. this._blendingFactor += blendingSpeed;
  50573. }
  50574. else {
  50575. this._currentValue = currentValue;
  50576. }
  50577. if (weight !== -1.0) {
  50578. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50579. }
  50580. else {
  50581. destination[path] = this._currentValue;
  50582. }
  50583. if (target.markAsDirty) {
  50584. target.markAsDirty(this._animation.targetProperty);
  50585. }
  50586. };
  50587. /**
  50588. * Gets the loop pmode of the runtime animation
  50589. * @returns Loop Mode
  50590. */
  50591. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50592. if (this._target && this._target.animationPropertiesOverride) {
  50593. return this._target.animationPropertiesOverride.loopMode;
  50594. }
  50595. return this._animation.loopMode;
  50596. };
  50597. /**
  50598. * Move the current animation to a given frame
  50599. * @param frame defines the frame to move to
  50600. */
  50601. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50602. var keys = this._animation.getKeys();
  50603. if (frame < keys[0].frame) {
  50604. frame = keys[0].frame;
  50605. }
  50606. else if (frame > keys[keys.length - 1].frame) {
  50607. frame = keys[keys.length - 1].frame;
  50608. }
  50609. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50610. this.setValue(currentValue, -1);
  50611. };
  50612. /**
  50613. * @hidden Internal use only
  50614. */
  50615. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50616. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50617. this._ratioOffset = this._previousRatio - newRatio;
  50618. };
  50619. /**
  50620. * Execute the current animation
  50621. * @param delay defines the delay to add to the current frame
  50622. * @param from defines the lower bound of the animation range
  50623. * @param to defines the upper bound of the animation range
  50624. * @param loop defines if the current animation must loop
  50625. * @param speedRatio defines the current speed ratio
  50626. * @param weight defines the weight of the animation (default is -1 so no weight)
  50627. * @returns a boolean indicating if the animation is running
  50628. */
  50629. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50630. if (weight === void 0) { weight = -1.0; }
  50631. var targetPropertyPath = this._animation.targetPropertyPath;
  50632. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50633. this._stopped = true;
  50634. return false;
  50635. }
  50636. var returnValue = true;
  50637. var keys = this._animation.getKeys();
  50638. // Adding a start key at frame 0 if missing
  50639. if (keys[0].frame !== 0) {
  50640. var newKey = { frame: 0, value: keys[0].value };
  50641. keys.splice(0, 0, newKey);
  50642. }
  50643. // Adding a duplicate key when there is only one key at frame zero
  50644. else if (keys.length === 1) {
  50645. var newKey = { frame: 0.001, value: keys[0].value };
  50646. keys.push(newKey);
  50647. }
  50648. // Check limits
  50649. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50650. from = keys[0].frame;
  50651. }
  50652. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50653. to = keys[keys.length - 1].frame;
  50654. }
  50655. //to and from cannot be the same key
  50656. if (from === to) {
  50657. if (from > keys[0].frame) {
  50658. from--;
  50659. }
  50660. else if (to < keys[keys.length - 1].frame) {
  50661. to++;
  50662. }
  50663. }
  50664. // Compute ratio
  50665. var range = to - from;
  50666. var offsetValue;
  50667. // ratio represents the frame delta between from and to
  50668. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50669. var highLimitValue = 0;
  50670. this._previousDelay = delay;
  50671. this._previousRatio = ratio;
  50672. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50673. returnValue = false;
  50674. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50675. }
  50676. else {
  50677. // Get max value if required
  50678. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50679. var keyOffset = to.toString() + from.toString();
  50680. if (!this._offsetsCache[keyOffset]) {
  50681. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50682. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50683. switch (this._animation.dataType) {
  50684. // Float
  50685. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50686. this._offsetsCache[keyOffset] = toValue - fromValue;
  50687. break;
  50688. // Quaternion
  50689. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50690. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50691. break;
  50692. // Vector3
  50693. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50694. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50695. // Vector2
  50696. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50697. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50698. // Size
  50699. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50700. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50701. // Color3
  50702. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50703. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50704. default:
  50705. break;
  50706. }
  50707. this._highLimitsCache[keyOffset] = toValue;
  50708. }
  50709. highLimitValue = this._highLimitsCache[keyOffset];
  50710. offsetValue = this._offsetsCache[keyOffset];
  50711. }
  50712. }
  50713. if (offsetValue === undefined) {
  50714. switch (this._animation.dataType) {
  50715. // Float
  50716. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50717. offsetValue = 0;
  50718. break;
  50719. // Quaternion
  50720. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50721. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50722. break;
  50723. // Vector3
  50724. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50725. offsetValue = BABYLON.Vector3.Zero();
  50726. break;
  50727. // Vector2
  50728. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50729. offsetValue = BABYLON.Vector2.Zero();
  50730. break;
  50731. // Size
  50732. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50733. offsetValue = BABYLON.Size.Zero();
  50734. break;
  50735. // Color3
  50736. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50737. offsetValue = BABYLON.Color3.Black();
  50738. }
  50739. }
  50740. // Compute value
  50741. var repeatCount = (ratio / range) >> 0;
  50742. var currentFrame = returnValue ? from + ratio % range : to;
  50743. // Need to normalize?
  50744. if (this._host && this._host.syncRoot) {
  50745. var syncRoot = this._host.syncRoot;
  50746. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50747. currentFrame = from + (to - from) * hostNormalizedFrame;
  50748. }
  50749. // Reset events if looping
  50750. var events = this._events;
  50751. if (range > 0 && this.currentFrame > currentFrame ||
  50752. range < 0 && this.currentFrame < currentFrame) {
  50753. // Need to reset animation events
  50754. for (var index = 0; index < events.length; index++) {
  50755. if (!events[index].onlyOnce) {
  50756. // reset event, the animation is looping
  50757. events[index].isDone = false;
  50758. }
  50759. }
  50760. }
  50761. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50762. // Set value
  50763. this.setValue(currentValue, weight);
  50764. // Check events
  50765. for (var index = 0; index < events.length; index++) {
  50766. // Make sure current frame has passed event frame and that event frame is within the current range
  50767. // Also, handle both forward and reverse animations
  50768. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50769. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50770. var event = events[index];
  50771. if (!event.isDone) {
  50772. // If event should be done only once, remove it.
  50773. if (event.onlyOnce) {
  50774. events.splice(index, 1);
  50775. index--;
  50776. }
  50777. event.isDone = true;
  50778. event.action();
  50779. } // Don't do anything if the event has already be done.
  50780. }
  50781. }
  50782. if (!returnValue) {
  50783. this._stopped = true;
  50784. }
  50785. return returnValue;
  50786. };
  50787. return RuntimeAnimation;
  50788. }());
  50789. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50790. })(BABYLON || (BABYLON = {}));
  50791. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50792. var BABYLON;
  50793. (function (BABYLON) {
  50794. /**
  50795. * Class used to store an actual running animation
  50796. */
  50797. var Animatable = /** @class */ (function () {
  50798. /**
  50799. * Creates a new Animatable
  50800. * @param scene defines the hosting scene
  50801. * @param target defines the target object
  50802. * @param fromFrame defines the starting frame number (default is 0)
  50803. * @param toFrame defines the ending frame number (default is 100)
  50804. * @param loopAnimation defines if the animation must loop (default is false)
  50805. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  50806. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  50807. * @param animations defines a group of animation to add to the new Animatable
  50808. */
  50809. function Animatable(scene,
  50810. /** defines the target object */
  50811. target,
  50812. /** defines the starting frame number (default is 0) */
  50813. fromFrame,
  50814. /** defines the ending frame number (default is 100) */
  50815. toFrame,
  50816. /** defines if the animation must loop (default is false) */
  50817. loopAnimation, speedRatio,
  50818. /** defines a callback to call when animation ends if it is not looping */
  50819. onAnimationEnd, animations) {
  50820. if (fromFrame === void 0) { fromFrame = 0; }
  50821. if (toFrame === void 0) { toFrame = 100; }
  50822. if (loopAnimation === void 0) { loopAnimation = false; }
  50823. if (speedRatio === void 0) { speedRatio = 1.0; }
  50824. this.target = target;
  50825. this.fromFrame = fromFrame;
  50826. this.toFrame = toFrame;
  50827. this.loopAnimation = loopAnimation;
  50828. this.onAnimationEnd = onAnimationEnd;
  50829. this._localDelayOffset = null;
  50830. this._pausedDelay = null;
  50831. this._runtimeAnimations = new Array();
  50832. this._paused = false;
  50833. this._speedRatio = 1;
  50834. this._weight = -1.0;
  50835. /**
  50836. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  50837. * This will only apply for non looping animation (default is true)
  50838. */
  50839. this.disposeOnEnd = true;
  50840. /**
  50841. * Gets a boolean indicating if the animation has started
  50842. */
  50843. this.animationStarted = false;
  50844. /**
  50845. * Observer raised when the animation ends
  50846. */
  50847. this.onAnimationEndObservable = new BABYLON.Observable();
  50848. this._scene = scene;
  50849. if (animations) {
  50850. this.appendAnimations(target, animations);
  50851. }
  50852. this._speedRatio = speedRatio;
  50853. scene._activeAnimatables.push(this);
  50854. }
  50855. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50856. /**
  50857. * Gets the root Animatable used to synchronize and normalize animations
  50858. */
  50859. get: function () {
  50860. return this._syncRoot;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50866. /**
  50867. * Gets the current frame of the first RuntimeAnimation
  50868. * Used to synchronize Animatables
  50869. */
  50870. get: function () {
  50871. if (this._runtimeAnimations.length === 0) {
  50872. return 0;
  50873. }
  50874. return this._runtimeAnimations[0].currentFrame;
  50875. },
  50876. enumerable: true,
  50877. configurable: true
  50878. });
  50879. Object.defineProperty(Animatable.prototype, "weight", {
  50880. /**
  50881. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50882. */
  50883. get: function () {
  50884. return this._weight;
  50885. },
  50886. set: function (value) {
  50887. if (value === -1) { // -1 is ok and means no weight
  50888. this._weight = -1;
  50889. return;
  50890. }
  50891. // Else weight must be in [0, 1] range
  50892. this._weight = Math.min(Math.max(value, 0), 1.0);
  50893. },
  50894. enumerable: true,
  50895. configurable: true
  50896. });
  50897. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50898. /**
  50899. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50900. */
  50901. get: function () {
  50902. return this._speedRatio;
  50903. },
  50904. set: function (value) {
  50905. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50906. var animation = this._runtimeAnimations[index];
  50907. animation._prepareForSpeedRatioChange(value);
  50908. }
  50909. this._speedRatio = value;
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. // Methods
  50915. /**
  50916. * Synchronize and normalize current Animatable with a source Animatable
  50917. * This is useful when using animation weights and when animations are not of the same length
  50918. * @param root defines the root Animatable to synchronize with
  50919. * @returns the current Animatable
  50920. */
  50921. Animatable.prototype.syncWith = function (root) {
  50922. this._syncRoot = root;
  50923. if (root) {
  50924. // Make sure this animatable will animate after the root
  50925. var index = this._scene._activeAnimatables.indexOf(this);
  50926. if (index > -1) {
  50927. this._scene._activeAnimatables.splice(index, 1);
  50928. this._scene._activeAnimatables.push(this);
  50929. }
  50930. }
  50931. return this;
  50932. };
  50933. /**
  50934. * Gets the list of runtime animations
  50935. * @returns an array of RuntimeAnimation
  50936. */
  50937. Animatable.prototype.getAnimations = function () {
  50938. return this._runtimeAnimations;
  50939. };
  50940. /**
  50941. * Adds more animations to the current animatable
  50942. * @param target defines the target of the animations
  50943. * @param animations defines the new animations to add
  50944. */
  50945. Animatable.prototype.appendAnimations = function (target, animations) {
  50946. for (var index = 0; index < animations.length; index++) {
  50947. var animation = animations[index];
  50948. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50949. }
  50950. };
  50951. /**
  50952. * Gets the source animation for a specific property
  50953. * @param property defines the propertyu to look for
  50954. * @returns null or the source animation for the given property
  50955. */
  50956. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50957. var runtimeAnimations = this._runtimeAnimations;
  50958. for (var index = 0; index < runtimeAnimations.length; index++) {
  50959. if (runtimeAnimations[index].animation.targetProperty === property) {
  50960. return runtimeAnimations[index].animation;
  50961. }
  50962. }
  50963. return null;
  50964. };
  50965. /**
  50966. * Gets the runtime animation for a specific property
  50967. * @param property defines the propertyu to look for
  50968. * @returns null or the runtime animation for the given property
  50969. */
  50970. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50971. var runtimeAnimations = this._runtimeAnimations;
  50972. for (var index = 0; index < runtimeAnimations.length; index++) {
  50973. if (runtimeAnimations[index].animation.targetProperty === property) {
  50974. return runtimeAnimations[index];
  50975. }
  50976. }
  50977. return null;
  50978. };
  50979. /**
  50980. * Resets the animatable to its original state
  50981. */
  50982. Animatable.prototype.reset = function () {
  50983. var runtimeAnimations = this._runtimeAnimations;
  50984. for (var index = 0; index < runtimeAnimations.length; index++) {
  50985. runtimeAnimations[index].reset(true);
  50986. }
  50987. this._localDelayOffset = null;
  50988. this._pausedDelay = null;
  50989. };
  50990. /**
  50991. * Allows the animatable to blend with current running animations
  50992. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  50993. * @param blendingSpeed defines the blending speed to use
  50994. */
  50995. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50996. var runtimeAnimations = this._runtimeAnimations;
  50997. for (var index = 0; index < runtimeAnimations.length; index++) {
  50998. runtimeAnimations[index].animation.enableBlending = true;
  50999. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51000. }
  51001. };
  51002. /**
  51003. * Disable animation blending
  51004. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51005. */
  51006. Animatable.prototype.disableBlending = function () {
  51007. var runtimeAnimations = this._runtimeAnimations;
  51008. for (var index = 0; index < runtimeAnimations.length; index++) {
  51009. runtimeAnimations[index].animation.enableBlending = false;
  51010. }
  51011. };
  51012. /**
  51013. * Jump directly to a given frame
  51014. * @param frame defines the frame to jump to
  51015. */
  51016. Animatable.prototype.goToFrame = function (frame) {
  51017. var runtimeAnimations = this._runtimeAnimations;
  51018. if (runtimeAnimations[0]) {
  51019. var fps = runtimeAnimations[0].animation.framePerSecond;
  51020. var currentFrame = runtimeAnimations[0].currentFrame;
  51021. var adjustTime = frame - currentFrame;
  51022. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51023. if (this._localDelayOffset === null) {
  51024. this._localDelayOffset = 0;
  51025. }
  51026. this._localDelayOffset -= delay;
  51027. }
  51028. for (var index = 0; index < runtimeAnimations.length; index++) {
  51029. runtimeAnimations[index].goToFrame(frame);
  51030. }
  51031. };
  51032. /**
  51033. * Pause the animation
  51034. */
  51035. Animatable.prototype.pause = function () {
  51036. if (this._paused) {
  51037. return;
  51038. }
  51039. this._paused = true;
  51040. };
  51041. /**
  51042. * Restart the animation
  51043. */
  51044. Animatable.prototype.restart = function () {
  51045. this._paused = false;
  51046. };
  51047. Animatable.prototype._raiseOnAnimationEnd = function () {
  51048. if (this.onAnimationEnd) {
  51049. this.onAnimationEnd();
  51050. }
  51051. this.onAnimationEndObservable.notifyObservers(this);
  51052. };
  51053. /**
  51054. * Stop and delete the current animation
  51055. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51056. * @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)
  51057. */
  51058. Animatable.prototype.stop = function (animationName, targetMask) {
  51059. if (animationName || targetMask) {
  51060. var idx = this._scene._activeAnimatables.indexOf(this);
  51061. if (idx > -1) {
  51062. var runtimeAnimations = this._runtimeAnimations;
  51063. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51064. var runtimeAnimation = runtimeAnimations[index];
  51065. if (animationName && runtimeAnimation.animation.name != animationName) {
  51066. continue;
  51067. }
  51068. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51069. continue;
  51070. }
  51071. runtimeAnimation.dispose();
  51072. runtimeAnimations.splice(index, 1);
  51073. }
  51074. if (runtimeAnimations.length == 0) {
  51075. this._scene._activeAnimatables.splice(idx, 1);
  51076. this._raiseOnAnimationEnd();
  51077. }
  51078. }
  51079. }
  51080. else {
  51081. var index = this._scene._activeAnimatables.indexOf(this);
  51082. if (index > -1) {
  51083. this._scene._activeAnimatables.splice(index, 1);
  51084. var runtimeAnimations = this._runtimeAnimations;
  51085. for (var index = 0; index < runtimeAnimations.length; index++) {
  51086. runtimeAnimations[index].dispose();
  51087. }
  51088. this._raiseOnAnimationEnd();
  51089. }
  51090. }
  51091. };
  51092. /**
  51093. * Wait asynchronously for the animation to end
  51094. * @returns a promise which will be fullfilled when the animation ends
  51095. */
  51096. Animatable.prototype.waitAsync = function () {
  51097. var _this = this;
  51098. return new Promise(function (resolve, reject) {
  51099. _this.onAnimationEndObservable.add(function () {
  51100. resolve(_this);
  51101. }, undefined, undefined, _this, true);
  51102. });
  51103. };
  51104. /** @hidden */
  51105. Animatable.prototype._animate = function (delay) {
  51106. if (this._paused) {
  51107. this.animationStarted = false;
  51108. if (this._pausedDelay === null) {
  51109. this._pausedDelay = delay;
  51110. }
  51111. return true;
  51112. }
  51113. if (this._localDelayOffset === null) {
  51114. this._localDelayOffset = delay;
  51115. this._pausedDelay = null;
  51116. }
  51117. else if (this._pausedDelay !== null) {
  51118. this._localDelayOffset += delay - this._pausedDelay;
  51119. this._pausedDelay = null;
  51120. }
  51121. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51122. return true;
  51123. }
  51124. // Animating
  51125. var running = false;
  51126. var runtimeAnimations = this._runtimeAnimations;
  51127. var index;
  51128. for (index = 0; index < runtimeAnimations.length; index++) {
  51129. var animation = runtimeAnimations[index];
  51130. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51131. running = running || isRunning;
  51132. }
  51133. this.animationStarted = running;
  51134. if (!running) {
  51135. if (this.disposeOnEnd) {
  51136. // Remove from active animatables
  51137. index = this._scene._activeAnimatables.indexOf(this);
  51138. this._scene._activeAnimatables.splice(index, 1);
  51139. // Dispose all runtime animations
  51140. for (index = 0; index < runtimeAnimations.length; index++) {
  51141. runtimeAnimations[index].dispose();
  51142. }
  51143. }
  51144. this._raiseOnAnimationEnd();
  51145. if (this.disposeOnEnd) {
  51146. this.onAnimationEnd = null;
  51147. this.onAnimationEndObservable.clear();
  51148. }
  51149. }
  51150. return running;
  51151. };
  51152. return Animatable;
  51153. }());
  51154. BABYLON.Animatable = Animatable;
  51155. })(BABYLON || (BABYLON = {}));
  51156. //# sourceMappingURL=babylon.animatable.js.map
  51157. var BABYLON;
  51158. (function (BABYLON) {
  51159. var EasingFunction = /** @class */ (function () {
  51160. function EasingFunction() {
  51161. // Properties
  51162. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51163. }
  51164. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51165. get: function () {
  51166. return EasingFunction._EASINGMODE_EASEIN;
  51167. },
  51168. enumerable: true,
  51169. configurable: true
  51170. });
  51171. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51172. get: function () {
  51173. return EasingFunction._EASINGMODE_EASEOUT;
  51174. },
  51175. enumerable: true,
  51176. configurable: true
  51177. });
  51178. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51179. get: function () {
  51180. return EasingFunction._EASINGMODE_EASEINOUT;
  51181. },
  51182. enumerable: true,
  51183. configurable: true
  51184. });
  51185. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51186. var n = Math.min(Math.max(easingMode, 0), 2);
  51187. this._easingMode = n;
  51188. };
  51189. EasingFunction.prototype.getEasingMode = function () {
  51190. return this._easingMode;
  51191. };
  51192. EasingFunction.prototype.easeInCore = function (gradient) {
  51193. throw new Error('You must implement this method');
  51194. };
  51195. EasingFunction.prototype.ease = function (gradient) {
  51196. switch (this._easingMode) {
  51197. case EasingFunction.EASINGMODE_EASEIN:
  51198. return this.easeInCore(gradient);
  51199. case EasingFunction.EASINGMODE_EASEOUT:
  51200. return (1 - this.easeInCore(1 - gradient));
  51201. }
  51202. if (gradient >= 0.5) {
  51203. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51204. }
  51205. return (this.easeInCore(gradient * 2) * 0.5);
  51206. };
  51207. //Statics
  51208. EasingFunction._EASINGMODE_EASEIN = 0;
  51209. EasingFunction._EASINGMODE_EASEOUT = 1;
  51210. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51211. return EasingFunction;
  51212. }());
  51213. BABYLON.EasingFunction = EasingFunction;
  51214. var CircleEase = /** @class */ (function (_super) {
  51215. __extends(CircleEase, _super);
  51216. function CircleEase() {
  51217. return _super !== null && _super.apply(this, arguments) || this;
  51218. }
  51219. CircleEase.prototype.easeInCore = function (gradient) {
  51220. gradient = Math.max(0, Math.min(1, gradient));
  51221. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51222. };
  51223. return CircleEase;
  51224. }(EasingFunction));
  51225. BABYLON.CircleEase = CircleEase;
  51226. var BackEase = /** @class */ (function (_super) {
  51227. __extends(BackEase, _super);
  51228. function BackEase(amplitude) {
  51229. if (amplitude === void 0) { amplitude = 1; }
  51230. var _this = _super.call(this) || this;
  51231. _this.amplitude = amplitude;
  51232. return _this;
  51233. }
  51234. BackEase.prototype.easeInCore = function (gradient) {
  51235. var num = Math.max(0, this.amplitude);
  51236. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51237. };
  51238. return BackEase;
  51239. }(EasingFunction));
  51240. BABYLON.BackEase = BackEase;
  51241. var BounceEase = /** @class */ (function (_super) {
  51242. __extends(BounceEase, _super);
  51243. function BounceEase(bounces, bounciness) {
  51244. if (bounces === void 0) { bounces = 3; }
  51245. if (bounciness === void 0) { bounciness = 2; }
  51246. var _this = _super.call(this) || this;
  51247. _this.bounces = bounces;
  51248. _this.bounciness = bounciness;
  51249. return _this;
  51250. }
  51251. BounceEase.prototype.easeInCore = function (gradient) {
  51252. var y = Math.max(0.0, this.bounces);
  51253. var bounciness = this.bounciness;
  51254. if (bounciness <= 1.0) {
  51255. bounciness = 1.001;
  51256. }
  51257. var num9 = Math.pow(bounciness, y);
  51258. var num5 = 1.0 - bounciness;
  51259. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51260. var num15 = gradient * num4;
  51261. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51262. var num3 = Math.floor(num65);
  51263. var num13 = num3 + 1.0;
  51264. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51265. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51266. var num7 = (num8 + num12) * 0.5;
  51267. var num6 = gradient - num7;
  51268. var num2 = num7 - num8;
  51269. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51270. };
  51271. return BounceEase;
  51272. }(EasingFunction));
  51273. BABYLON.BounceEase = BounceEase;
  51274. var CubicEase = /** @class */ (function (_super) {
  51275. __extends(CubicEase, _super);
  51276. function CubicEase() {
  51277. return _super !== null && _super.apply(this, arguments) || this;
  51278. }
  51279. CubicEase.prototype.easeInCore = function (gradient) {
  51280. return (gradient * gradient * gradient);
  51281. };
  51282. return CubicEase;
  51283. }(EasingFunction));
  51284. BABYLON.CubicEase = CubicEase;
  51285. var ElasticEase = /** @class */ (function (_super) {
  51286. __extends(ElasticEase, _super);
  51287. function ElasticEase(oscillations, springiness) {
  51288. if (oscillations === void 0) { oscillations = 3; }
  51289. if (springiness === void 0) { springiness = 3; }
  51290. var _this = _super.call(this) || this;
  51291. _this.oscillations = oscillations;
  51292. _this.springiness = springiness;
  51293. return _this;
  51294. }
  51295. ElasticEase.prototype.easeInCore = function (gradient) {
  51296. var num2;
  51297. var num3 = Math.max(0.0, this.oscillations);
  51298. var num = Math.max(0.0, this.springiness);
  51299. if (num == 0) {
  51300. num2 = gradient;
  51301. }
  51302. else {
  51303. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51304. }
  51305. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51306. };
  51307. return ElasticEase;
  51308. }(EasingFunction));
  51309. BABYLON.ElasticEase = ElasticEase;
  51310. var ExponentialEase = /** @class */ (function (_super) {
  51311. __extends(ExponentialEase, _super);
  51312. function ExponentialEase(exponent) {
  51313. if (exponent === void 0) { exponent = 2; }
  51314. var _this = _super.call(this) || this;
  51315. _this.exponent = exponent;
  51316. return _this;
  51317. }
  51318. ExponentialEase.prototype.easeInCore = function (gradient) {
  51319. if (this.exponent <= 0) {
  51320. return gradient;
  51321. }
  51322. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51323. };
  51324. return ExponentialEase;
  51325. }(EasingFunction));
  51326. BABYLON.ExponentialEase = ExponentialEase;
  51327. var PowerEase = /** @class */ (function (_super) {
  51328. __extends(PowerEase, _super);
  51329. function PowerEase(power) {
  51330. if (power === void 0) { power = 2; }
  51331. var _this = _super.call(this) || this;
  51332. _this.power = power;
  51333. return _this;
  51334. }
  51335. PowerEase.prototype.easeInCore = function (gradient) {
  51336. var y = Math.max(0.0, this.power);
  51337. return Math.pow(gradient, y);
  51338. };
  51339. return PowerEase;
  51340. }(EasingFunction));
  51341. BABYLON.PowerEase = PowerEase;
  51342. var QuadraticEase = /** @class */ (function (_super) {
  51343. __extends(QuadraticEase, _super);
  51344. function QuadraticEase() {
  51345. return _super !== null && _super.apply(this, arguments) || this;
  51346. }
  51347. QuadraticEase.prototype.easeInCore = function (gradient) {
  51348. return (gradient * gradient);
  51349. };
  51350. return QuadraticEase;
  51351. }(EasingFunction));
  51352. BABYLON.QuadraticEase = QuadraticEase;
  51353. var QuarticEase = /** @class */ (function (_super) {
  51354. __extends(QuarticEase, _super);
  51355. function QuarticEase() {
  51356. return _super !== null && _super.apply(this, arguments) || this;
  51357. }
  51358. QuarticEase.prototype.easeInCore = function (gradient) {
  51359. return (gradient * gradient * gradient * gradient);
  51360. };
  51361. return QuarticEase;
  51362. }(EasingFunction));
  51363. BABYLON.QuarticEase = QuarticEase;
  51364. var QuinticEase = /** @class */ (function (_super) {
  51365. __extends(QuinticEase, _super);
  51366. function QuinticEase() {
  51367. return _super !== null && _super.apply(this, arguments) || this;
  51368. }
  51369. QuinticEase.prototype.easeInCore = function (gradient) {
  51370. return (gradient * gradient * gradient * gradient * gradient);
  51371. };
  51372. return QuinticEase;
  51373. }(EasingFunction));
  51374. BABYLON.QuinticEase = QuinticEase;
  51375. var SineEase = /** @class */ (function (_super) {
  51376. __extends(SineEase, _super);
  51377. function SineEase() {
  51378. return _super !== null && _super.apply(this, arguments) || this;
  51379. }
  51380. SineEase.prototype.easeInCore = function (gradient) {
  51381. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51382. };
  51383. return SineEase;
  51384. }(EasingFunction));
  51385. BABYLON.SineEase = SineEase;
  51386. var BezierCurveEase = /** @class */ (function (_super) {
  51387. __extends(BezierCurveEase, _super);
  51388. function BezierCurveEase(x1, y1, x2, y2) {
  51389. if (x1 === void 0) { x1 = 0; }
  51390. if (y1 === void 0) { y1 = 0; }
  51391. if (x2 === void 0) { x2 = 1; }
  51392. if (y2 === void 0) { y2 = 1; }
  51393. var _this = _super.call(this) || this;
  51394. _this.x1 = x1;
  51395. _this.y1 = y1;
  51396. _this.x2 = x2;
  51397. _this.y2 = y2;
  51398. return _this;
  51399. }
  51400. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51401. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51402. };
  51403. return BezierCurveEase;
  51404. }(EasingFunction));
  51405. BABYLON.BezierCurveEase = BezierCurveEase;
  51406. })(BABYLON || (BABYLON = {}));
  51407. //# sourceMappingURL=babylon.easing.js.map
  51408. var BABYLON;
  51409. (function (BABYLON) {
  51410. /**
  51411. * A Condition applied to an Action
  51412. */
  51413. var Condition = /** @class */ (function () {
  51414. /**
  51415. * Creates a new Condition
  51416. * @param actionManager the manager of the action the condition is applied to
  51417. */
  51418. function Condition(actionManager) {
  51419. this._actionManager = actionManager;
  51420. }
  51421. /**
  51422. * Check if the current condition is valid
  51423. * @returns a boolean
  51424. */
  51425. Condition.prototype.isValid = function () {
  51426. return true;
  51427. };
  51428. /**
  51429. * Internal only
  51430. * @hidden
  51431. */
  51432. Condition.prototype._getProperty = function (propertyPath) {
  51433. return this._actionManager._getProperty(propertyPath);
  51434. };
  51435. /**
  51436. * Internal only
  51437. * @hidden
  51438. */
  51439. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51440. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51441. };
  51442. /**
  51443. * Serialize placeholder for child classes
  51444. * @returns the serialized object
  51445. */
  51446. Condition.prototype.serialize = function () {
  51447. };
  51448. /**
  51449. * Internal only
  51450. * @hidden
  51451. */
  51452. Condition.prototype._serialize = function (serializedCondition) {
  51453. return {
  51454. type: 2,
  51455. children: [],
  51456. name: serializedCondition.name,
  51457. properties: serializedCondition.properties
  51458. };
  51459. };
  51460. return Condition;
  51461. }());
  51462. BABYLON.Condition = Condition;
  51463. /**
  51464. * Defines specific conditional operators as extensions of Condition
  51465. */
  51466. var ValueCondition = /** @class */ (function (_super) {
  51467. __extends(ValueCondition, _super);
  51468. /**
  51469. * Creates a new ValueCondition
  51470. * @param actionManager manager for the action the condition applies to
  51471. * @param target for the action
  51472. * @param propertyPath path to specify the property of the target the conditional operator uses
  51473. * @param value the value compared by the conditional operator against the current value of the property
  51474. * @param operator the conditional operator, default ValueCondition.IsEqual
  51475. */
  51476. function ValueCondition(actionManager, target,
  51477. /** path to specify the property of the target the conditional operator uses */
  51478. propertyPath,
  51479. /** the value compared by the conditional operator against the current value of the property */
  51480. value,
  51481. /** the conditional operator, default ValueCondition.IsEqual */
  51482. operator) {
  51483. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51484. var _this = _super.call(this, actionManager) || this;
  51485. _this.propertyPath = propertyPath;
  51486. _this.value = value;
  51487. _this.operator = operator;
  51488. _this._target = target;
  51489. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51490. _this._property = _this._getProperty(_this.propertyPath);
  51491. return _this;
  51492. }
  51493. Object.defineProperty(ValueCondition, "IsEqual", {
  51494. /**
  51495. * returns the number for IsEqual
  51496. */
  51497. get: function () {
  51498. return ValueCondition._IsEqual;
  51499. },
  51500. enumerable: true,
  51501. configurable: true
  51502. });
  51503. Object.defineProperty(ValueCondition, "IsDifferent", {
  51504. /**
  51505. * Returns the number for IsDifferent
  51506. */
  51507. get: function () {
  51508. return ValueCondition._IsDifferent;
  51509. },
  51510. enumerable: true,
  51511. configurable: true
  51512. });
  51513. Object.defineProperty(ValueCondition, "IsGreater", {
  51514. /**
  51515. * Returns the number for IsGreater
  51516. */
  51517. get: function () {
  51518. return ValueCondition._IsGreater;
  51519. },
  51520. enumerable: true,
  51521. configurable: true
  51522. });
  51523. Object.defineProperty(ValueCondition, "IsLesser", {
  51524. /**
  51525. * Returns the number for IsLesser
  51526. */
  51527. get: function () {
  51528. return ValueCondition._IsLesser;
  51529. },
  51530. enumerable: true,
  51531. configurable: true
  51532. });
  51533. /**
  51534. * Compares the given value with the property value for the specified conditional operator
  51535. * @returns the result of the comparison
  51536. */
  51537. ValueCondition.prototype.isValid = function () {
  51538. switch (this.operator) {
  51539. case ValueCondition.IsGreater:
  51540. return this._effectiveTarget[this._property] > this.value;
  51541. case ValueCondition.IsLesser:
  51542. return this._effectiveTarget[this._property] < this.value;
  51543. case ValueCondition.IsEqual:
  51544. case ValueCondition.IsDifferent:
  51545. var check;
  51546. if (this.value.equals) {
  51547. check = this.value.equals(this._effectiveTarget[this._property]);
  51548. }
  51549. else {
  51550. check = this.value === this._effectiveTarget[this._property];
  51551. }
  51552. return this.operator === ValueCondition.IsEqual ? check : !check;
  51553. }
  51554. return false;
  51555. };
  51556. /**
  51557. * Serialize the ValueCondition into a JSON compatible object
  51558. * @returns serialization object
  51559. */
  51560. ValueCondition.prototype.serialize = function () {
  51561. return this._serialize({
  51562. name: "ValueCondition",
  51563. properties: [
  51564. BABYLON.Action._GetTargetProperty(this._target),
  51565. { name: "propertyPath", value: this.propertyPath },
  51566. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51567. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51568. ]
  51569. });
  51570. };
  51571. /**
  51572. * Gets the name of the conditional operator for the ValueCondition
  51573. * @param operator the conditional operator
  51574. * @returns the name
  51575. */
  51576. ValueCondition.GetOperatorName = function (operator) {
  51577. switch (operator) {
  51578. case ValueCondition._IsEqual: return "IsEqual";
  51579. case ValueCondition._IsDifferent: return "IsDifferent";
  51580. case ValueCondition._IsGreater: return "IsGreater";
  51581. case ValueCondition._IsLesser: return "IsLesser";
  51582. default: return "";
  51583. }
  51584. };
  51585. /**
  51586. * Internal only
  51587. * @hidden
  51588. */
  51589. ValueCondition._IsEqual = 0;
  51590. /**
  51591. * Internal only
  51592. * @hidden
  51593. */
  51594. ValueCondition._IsDifferent = 1;
  51595. /**
  51596. * Internal only
  51597. * @hidden
  51598. */
  51599. ValueCondition._IsGreater = 2;
  51600. /**
  51601. * Internal only
  51602. * @hidden
  51603. */
  51604. ValueCondition._IsLesser = 3;
  51605. return ValueCondition;
  51606. }(Condition));
  51607. BABYLON.ValueCondition = ValueCondition;
  51608. /**
  51609. * Defines a predicate condition as an extension of Condition
  51610. */
  51611. var PredicateCondition = /** @class */ (function (_super) {
  51612. __extends(PredicateCondition, _super);
  51613. /**
  51614. * Creates a new PredicateCondition
  51615. * @param actionManager manager for the action the condition applies to
  51616. * @param predicate defines the predicate function used to validate the condition
  51617. */
  51618. function PredicateCondition(actionManager,
  51619. /** defines the predicate function used to validate the condition */
  51620. predicate) {
  51621. var _this = _super.call(this, actionManager) || this;
  51622. _this.predicate = predicate;
  51623. return _this;
  51624. }
  51625. /**
  51626. * @returns the validity of the predicate condition
  51627. */
  51628. PredicateCondition.prototype.isValid = function () {
  51629. return this.predicate();
  51630. };
  51631. return PredicateCondition;
  51632. }(Condition));
  51633. BABYLON.PredicateCondition = PredicateCondition;
  51634. /**
  51635. * Defines a state condition as an extension of Condition
  51636. */
  51637. var StateCondition = /** @class */ (function (_super) {
  51638. __extends(StateCondition, _super);
  51639. /**
  51640. * Creates a new StateCondition
  51641. * @param actionManager manager for the action the condition applies to
  51642. * @param target of the condition
  51643. * @param value to compare with target state
  51644. */
  51645. function StateCondition(actionManager, target, value) {
  51646. var _this = _super.call(this, actionManager) || this;
  51647. _this.value = value;
  51648. _this._target = target;
  51649. return _this;
  51650. }
  51651. /**
  51652. * @returns the validity of the state
  51653. */
  51654. StateCondition.prototype.isValid = function () {
  51655. return this._target.state === this.value;
  51656. };
  51657. /**
  51658. * Serialize the StateCondition into a JSON compatible object
  51659. * @returns serialization object
  51660. */
  51661. StateCondition.prototype.serialize = function () {
  51662. return this._serialize({
  51663. name: "StateCondition",
  51664. properties: [
  51665. BABYLON.Action._GetTargetProperty(this._target),
  51666. { name: "value", value: this.value }
  51667. ]
  51668. });
  51669. };
  51670. return StateCondition;
  51671. }(Condition));
  51672. BABYLON.StateCondition = StateCondition;
  51673. })(BABYLON || (BABYLON = {}));
  51674. //# sourceMappingURL=babylon.condition.js.map
  51675. var BABYLON;
  51676. (function (BABYLON) {
  51677. /**
  51678. * The action to be carried out following a trigger
  51679. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51680. */
  51681. var Action = /** @class */ (function () {
  51682. /**
  51683. * Creates a new Action
  51684. * @param triggerOptions the trigger, with or without parameters, for the action
  51685. * @param condition an optional determinant of action
  51686. */
  51687. function Action(
  51688. /** the trigger, with or without parameters, for the action */
  51689. triggerOptions, condition) {
  51690. this.triggerOptions = triggerOptions;
  51691. /**
  51692. * An event triggered prior to action being executed.
  51693. */
  51694. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51695. if (triggerOptions.parameter) {
  51696. this.trigger = triggerOptions.trigger;
  51697. this._triggerParameter = triggerOptions.parameter;
  51698. }
  51699. else {
  51700. this.trigger = triggerOptions;
  51701. }
  51702. this._nextActiveAction = this;
  51703. this._condition = condition;
  51704. }
  51705. /**
  51706. * Internal only
  51707. * @hidden
  51708. */
  51709. Action.prototype._prepare = function () {
  51710. };
  51711. /**
  51712. * Gets the trigger parameters
  51713. * @returns the trigger parameters
  51714. */
  51715. Action.prototype.getTriggerParameter = function () {
  51716. return this._triggerParameter;
  51717. };
  51718. /**
  51719. * Internal only - executes current action event
  51720. * @hidden
  51721. */
  51722. Action.prototype._executeCurrent = function (evt) {
  51723. if (this._nextActiveAction._condition) {
  51724. var condition = this._nextActiveAction._condition;
  51725. var currentRenderId = this._actionManager.getScene().getRenderId();
  51726. // We cache the current evaluation for the current frame
  51727. if (condition._evaluationId === currentRenderId) {
  51728. if (!condition._currentResult) {
  51729. return;
  51730. }
  51731. }
  51732. else {
  51733. condition._evaluationId = currentRenderId;
  51734. if (!condition.isValid()) {
  51735. condition._currentResult = false;
  51736. return;
  51737. }
  51738. condition._currentResult = true;
  51739. }
  51740. }
  51741. this.onBeforeExecuteObservable.notifyObservers(this);
  51742. this._nextActiveAction.execute(evt);
  51743. this.skipToNextActiveAction();
  51744. };
  51745. /**
  51746. * Execute placeholder for child classes
  51747. * @param evt optional action event
  51748. */
  51749. Action.prototype.execute = function (evt) {
  51750. };
  51751. /**
  51752. * Skips to next active action
  51753. */
  51754. Action.prototype.skipToNextActiveAction = function () {
  51755. if (this._nextActiveAction._child) {
  51756. if (!this._nextActiveAction._child._actionManager) {
  51757. this._nextActiveAction._child._actionManager = this._actionManager;
  51758. }
  51759. this._nextActiveAction = this._nextActiveAction._child;
  51760. }
  51761. else {
  51762. this._nextActiveAction = this;
  51763. }
  51764. };
  51765. /**
  51766. * Adds action to chain of actions, may be a DoNothingAction
  51767. * @param action defines the next action to execute
  51768. * @returns The action passed in
  51769. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51770. */
  51771. Action.prototype.then = function (action) {
  51772. this._child = action;
  51773. action._actionManager = this._actionManager;
  51774. action._prepare();
  51775. return action;
  51776. };
  51777. /**
  51778. * Internal only
  51779. * @hidden
  51780. */
  51781. Action.prototype._getProperty = function (propertyPath) {
  51782. return this._actionManager._getProperty(propertyPath);
  51783. };
  51784. /**
  51785. * Internal only
  51786. * @hidden
  51787. */
  51788. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51789. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51790. };
  51791. /**
  51792. * Serialize placeholder for child classes
  51793. * @param parent of child
  51794. * @returns the serialized object
  51795. */
  51796. Action.prototype.serialize = function (parent) {
  51797. };
  51798. /**
  51799. * Internal only called by serialize
  51800. * @hidden
  51801. */
  51802. Action.prototype._serialize = function (serializedAction, parent) {
  51803. var serializationObject = {
  51804. type: 1,
  51805. children: [],
  51806. name: serializedAction.name,
  51807. properties: serializedAction.properties || []
  51808. };
  51809. // Serialize child
  51810. if (this._child) {
  51811. this._child.serialize(serializationObject);
  51812. }
  51813. // Check if "this" has a condition
  51814. if (this._condition) {
  51815. var serializedCondition = this._condition.serialize();
  51816. serializedCondition.children.push(serializationObject);
  51817. if (parent) {
  51818. parent.children.push(serializedCondition);
  51819. }
  51820. return serializedCondition;
  51821. }
  51822. if (parent) {
  51823. parent.children.push(serializationObject);
  51824. }
  51825. return serializationObject;
  51826. };
  51827. /**
  51828. * Internal only
  51829. * @hidden
  51830. */
  51831. Action._SerializeValueAsString = function (value) {
  51832. if (typeof value === "number") {
  51833. return value.toString();
  51834. }
  51835. if (typeof value === "boolean") {
  51836. return value ? "true" : "false";
  51837. }
  51838. if (value instanceof BABYLON.Vector2) {
  51839. return value.x + ", " + value.y;
  51840. }
  51841. if (value instanceof BABYLON.Vector3) {
  51842. return value.x + ", " + value.y + ", " + value.z;
  51843. }
  51844. if (value instanceof BABYLON.Color3) {
  51845. return value.r + ", " + value.g + ", " + value.b;
  51846. }
  51847. if (value instanceof BABYLON.Color4) {
  51848. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51849. }
  51850. return value; // string
  51851. };
  51852. /**
  51853. * Internal only
  51854. * @hidden
  51855. */
  51856. Action._GetTargetProperty = function (target) {
  51857. return {
  51858. name: "target",
  51859. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51860. : target instanceof BABYLON.Light ? "LightProperties"
  51861. : target instanceof BABYLON.Camera ? "CameraProperties"
  51862. : "SceneProperties",
  51863. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51864. };
  51865. };
  51866. return Action;
  51867. }());
  51868. BABYLON.Action = Action;
  51869. })(BABYLON || (BABYLON = {}));
  51870. //# sourceMappingURL=babylon.action.js.map
  51871. var BABYLON;
  51872. (function (BABYLON) {
  51873. /**
  51874. * ActionEvent is the event being sent when an action is triggered.
  51875. */
  51876. var ActionEvent = /** @class */ (function () {
  51877. /**
  51878. * Creates a new ActionEvent
  51879. * @param source The mesh or sprite that triggered the action
  51880. * @param pointerX The X mouse cursor position at the time of the event
  51881. * @param pointerY The Y mouse cursor position at the time of the event
  51882. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51883. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51884. * @param additionalData additional data for the event
  51885. */
  51886. function ActionEvent(
  51887. /** The mesh or sprite that triggered the action */
  51888. source,
  51889. /** The X mouse cursor position at the time of the event */
  51890. pointerX,
  51891. /** The Y mouse cursor position at the time of the event */
  51892. pointerY,
  51893. /** The mesh that is currently pointed at (can be null) */
  51894. meshUnderPointer,
  51895. /** the original (browser) event that triggered the ActionEvent */
  51896. sourceEvent,
  51897. /** additional data for the event */
  51898. additionalData) {
  51899. this.source = source;
  51900. this.pointerX = pointerX;
  51901. this.pointerY = pointerY;
  51902. this.meshUnderPointer = meshUnderPointer;
  51903. this.sourceEvent = sourceEvent;
  51904. this.additionalData = additionalData;
  51905. }
  51906. /**
  51907. * Helper function to auto-create an ActionEvent from a source mesh.
  51908. * @param source The source mesh that triggered the event
  51909. * @param evt The original (browser) event
  51910. * @param additionalData additional data for the event
  51911. * @returns the new ActionEvent
  51912. */
  51913. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51914. var scene = source.getScene();
  51915. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51916. };
  51917. /**
  51918. * Helper function to auto-create an ActionEvent from a source sprite
  51919. * @param source The source sprite that triggered the event
  51920. * @param scene Scene associated with the sprite
  51921. * @param evt The original (browser) event
  51922. * @param additionalData additional data for the event
  51923. * @returns the new ActionEvent
  51924. */
  51925. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51926. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51927. };
  51928. /**
  51929. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51930. * @param scene the scene where the event occurred
  51931. * @param evt The original (browser) event
  51932. * @returns the new ActionEvent
  51933. */
  51934. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51935. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51936. };
  51937. /**
  51938. * Helper function to auto-create an ActionEvent from a primitive
  51939. * @param prim defines the target primitive
  51940. * @param pointerPos defines the pointer position
  51941. * @param evt The original (browser) event
  51942. * @param additionalData additional data for the event
  51943. * @returns the new ActionEvent
  51944. */
  51945. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51946. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51947. };
  51948. return ActionEvent;
  51949. }());
  51950. BABYLON.ActionEvent = ActionEvent;
  51951. /**
  51952. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51953. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51954. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  51955. */
  51956. var ActionManager = /** @class */ (function () {
  51957. /**
  51958. * Creates a new action manager
  51959. * @param scene defines the hosting scene
  51960. */
  51961. function ActionManager(scene) {
  51962. // Members
  51963. /** Gets the list of actions */
  51964. this.actions = new Array();
  51965. /** Gets the cursor to use when hovering items */
  51966. this.hoverCursor = '';
  51967. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51968. scene.actionManagers.push(this);
  51969. }
  51970. Object.defineProperty(ActionManager, "NothingTrigger", {
  51971. /**
  51972. * Nothing
  51973. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51974. */
  51975. get: function () {
  51976. return ActionManager._NothingTrigger;
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51982. /**
  51983. * On pick
  51984. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51985. */
  51986. get: function () {
  51987. return ActionManager._OnPickTrigger;
  51988. },
  51989. enumerable: true,
  51990. configurable: true
  51991. });
  51992. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51993. /**
  51994. * On left pick
  51995. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  51996. */
  51997. get: function () {
  51998. return ActionManager._OnLeftPickTrigger;
  51999. },
  52000. enumerable: true,
  52001. configurable: true
  52002. });
  52003. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52004. /**
  52005. * On right pick
  52006. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52007. */
  52008. get: function () {
  52009. return ActionManager._OnRightPickTrigger;
  52010. },
  52011. enumerable: true,
  52012. configurable: true
  52013. });
  52014. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52015. /**
  52016. * On center pick
  52017. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52018. */
  52019. get: function () {
  52020. return ActionManager._OnCenterPickTrigger;
  52021. },
  52022. enumerable: true,
  52023. configurable: true
  52024. });
  52025. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52026. /**
  52027. * On pick down
  52028. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52029. */
  52030. get: function () {
  52031. return ActionManager._OnPickDownTrigger;
  52032. },
  52033. enumerable: true,
  52034. configurable: true
  52035. });
  52036. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52037. /**
  52038. * On double pick
  52039. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52040. */
  52041. get: function () {
  52042. return ActionManager._OnDoublePickTrigger;
  52043. },
  52044. enumerable: true,
  52045. configurable: true
  52046. });
  52047. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52048. /**
  52049. * On pick up
  52050. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52051. */
  52052. get: function () {
  52053. return ActionManager._OnPickUpTrigger;
  52054. },
  52055. enumerable: true,
  52056. configurable: true
  52057. });
  52058. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52059. /**
  52060. * On pick out.
  52061. * This trigger will only be raised if you also declared a OnPickDown
  52062. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52063. */
  52064. get: function () {
  52065. return ActionManager._OnPickOutTrigger;
  52066. },
  52067. enumerable: true,
  52068. configurable: true
  52069. });
  52070. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52071. /**
  52072. * On long press
  52073. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52074. */
  52075. get: function () {
  52076. return ActionManager._OnLongPressTrigger;
  52077. },
  52078. enumerable: true,
  52079. configurable: true
  52080. });
  52081. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52082. /**
  52083. * On pointer over
  52084. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52085. */
  52086. get: function () {
  52087. return ActionManager._OnPointerOverTrigger;
  52088. },
  52089. enumerable: true,
  52090. configurable: true
  52091. });
  52092. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52093. /**
  52094. * On pointer out
  52095. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52096. */
  52097. get: function () {
  52098. return ActionManager._OnPointerOutTrigger;
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52104. /**
  52105. * On every frame
  52106. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52107. */
  52108. get: function () {
  52109. return ActionManager._OnEveryFrameTrigger;
  52110. },
  52111. enumerable: true,
  52112. configurable: true
  52113. });
  52114. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52115. /**
  52116. * On intersection enter
  52117. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52118. */
  52119. get: function () {
  52120. return ActionManager._OnIntersectionEnterTrigger;
  52121. },
  52122. enumerable: true,
  52123. configurable: true
  52124. });
  52125. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52126. /**
  52127. * On intersection exit
  52128. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52129. */
  52130. get: function () {
  52131. return ActionManager._OnIntersectionExitTrigger;
  52132. },
  52133. enumerable: true,
  52134. configurable: true
  52135. });
  52136. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52137. /**
  52138. * On key down
  52139. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52140. */
  52141. get: function () {
  52142. return ActionManager._OnKeyDownTrigger;
  52143. },
  52144. enumerable: true,
  52145. configurable: true
  52146. });
  52147. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52148. /**
  52149. * On key up
  52150. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52151. */
  52152. get: function () {
  52153. return ActionManager._OnKeyUpTrigger;
  52154. },
  52155. enumerable: true,
  52156. configurable: true
  52157. });
  52158. // Methods
  52159. /**
  52160. * Releases all associated resources
  52161. */
  52162. ActionManager.prototype.dispose = function () {
  52163. var index = this._scene.actionManagers.indexOf(this);
  52164. for (var i = 0; i < this.actions.length; i++) {
  52165. var action = this.actions[i];
  52166. ActionManager.Triggers[action.trigger]--;
  52167. if (ActionManager.Triggers[action.trigger] === 0) {
  52168. delete ActionManager.Triggers[action.trigger];
  52169. }
  52170. }
  52171. if (index > -1) {
  52172. this._scene.actionManagers.splice(index, 1);
  52173. }
  52174. };
  52175. /**
  52176. * Gets hosting scene
  52177. * @returns the hosting scene
  52178. */
  52179. ActionManager.prototype.getScene = function () {
  52180. return this._scene;
  52181. };
  52182. /**
  52183. * Does this action manager handles actions of any of the given triggers
  52184. * @param triggers defines the triggers to be tested
  52185. * @return a boolean indicating whether one (or more) of the triggers is handled
  52186. */
  52187. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52188. for (var index = 0; index < this.actions.length; index++) {
  52189. var action = this.actions[index];
  52190. if (triggers.indexOf(action.trigger) > -1) {
  52191. return true;
  52192. }
  52193. }
  52194. return false;
  52195. };
  52196. /**
  52197. * Does this action manager handles actions of a given trigger
  52198. * @param trigger defines the trigger to be tested
  52199. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52200. * @return whether the trigger is handled
  52201. */
  52202. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52203. for (var index = 0; index < this.actions.length; index++) {
  52204. var action = this.actions[index];
  52205. if (action.trigger === trigger) {
  52206. if (parameterPredicate) {
  52207. if (parameterPredicate(action.getTriggerParameter())) {
  52208. return true;
  52209. }
  52210. }
  52211. else {
  52212. return true;
  52213. }
  52214. }
  52215. }
  52216. return false;
  52217. };
  52218. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52219. /**
  52220. * Does this action manager has pointer triggers
  52221. */
  52222. get: function () {
  52223. for (var index = 0; index < this.actions.length; index++) {
  52224. var action = this.actions[index];
  52225. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52226. return true;
  52227. }
  52228. }
  52229. return false;
  52230. },
  52231. enumerable: true,
  52232. configurable: true
  52233. });
  52234. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52235. /**
  52236. * Does this action manager has pick triggers
  52237. */
  52238. get: function () {
  52239. for (var index = 0; index < this.actions.length; index++) {
  52240. var action = this.actions[index];
  52241. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52242. return true;
  52243. }
  52244. }
  52245. return false;
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. Object.defineProperty(ActionManager, "HasTriggers", {
  52251. /**
  52252. * Does exist one action manager with at least one trigger
  52253. **/
  52254. get: function () {
  52255. for (var t in ActionManager.Triggers) {
  52256. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52257. return true;
  52258. }
  52259. }
  52260. return false;
  52261. },
  52262. enumerable: true,
  52263. configurable: true
  52264. });
  52265. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52266. /**
  52267. * Does exist one action manager with at least one pick trigger
  52268. **/
  52269. get: function () {
  52270. for (var t in ActionManager.Triggers) {
  52271. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52272. var t_int = parseInt(t);
  52273. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52274. return true;
  52275. }
  52276. }
  52277. }
  52278. return false;
  52279. },
  52280. enumerable: true,
  52281. configurable: true
  52282. });
  52283. /**
  52284. * Does exist one action manager that handles actions of a given trigger
  52285. * @param trigger defines the trigger to be tested
  52286. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52287. **/
  52288. ActionManager.HasSpecificTrigger = function (trigger) {
  52289. for (var t in ActionManager.Triggers) {
  52290. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52291. var t_int = parseInt(t);
  52292. if (t_int === trigger) {
  52293. return true;
  52294. }
  52295. }
  52296. }
  52297. return false;
  52298. };
  52299. /**
  52300. * Registers an action to this action manager
  52301. * @param action defines the action to be registered
  52302. * @return the action amended (prepared) after registration
  52303. */
  52304. ActionManager.prototype.registerAction = function (action) {
  52305. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52306. if (this.getScene().actionManager !== this) {
  52307. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52308. return null;
  52309. }
  52310. }
  52311. this.actions.push(action);
  52312. if (ActionManager.Triggers[action.trigger]) {
  52313. ActionManager.Triggers[action.trigger]++;
  52314. }
  52315. else {
  52316. ActionManager.Triggers[action.trigger] = 1;
  52317. }
  52318. action._actionManager = this;
  52319. action._prepare();
  52320. return action;
  52321. };
  52322. /**
  52323. * Unregisters an action to this action manager
  52324. * @param action defines the action to be unregistered
  52325. * @return a boolean indicating whether the action has been unregistered
  52326. */
  52327. ActionManager.prototype.unregisterAction = function (action) {
  52328. var index = this.actions.indexOf(action);
  52329. if (index !== -1) {
  52330. this.actions.splice(index, 1);
  52331. ActionManager.Triggers[action.trigger] -= 1;
  52332. if (ActionManager.Triggers[action.trigger] === 0) {
  52333. delete ActionManager.Triggers[action.trigger];
  52334. }
  52335. delete action._actionManager;
  52336. return true;
  52337. }
  52338. return false;
  52339. };
  52340. /**
  52341. * Process a specific trigger
  52342. * @param trigger defines the trigger to process
  52343. * @param evt defines the event details to be processed
  52344. */
  52345. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52346. for (var index = 0; index < this.actions.length; index++) {
  52347. var action = this.actions[index];
  52348. if (action.trigger === trigger) {
  52349. if (evt) {
  52350. if (trigger === ActionManager.OnKeyUpTrigger
  52351. || trigger === ActionManager.OnKeyDownTrigger) {
  52352. var parameter = action.getTriggerParameter();
  52353. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52354. if (!parameter.toLowerCase) {
  52355. continue;
  52356. }
  52357. var lowerCase = parameter.toLowerCase();
  52358. if (lowerCase !== evt.sourceEvent.key) {
  52359. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52360. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52361. if (actualkey !== lowerCase) {
  52362. continue;
  52363. }
  52364. }
  52365. }
  52366. }
  52367. }
  52368. action._executeCurrent(evt);
  52369. }
  52370. }
  52371. };
  52372. /** @hidden */
  52373. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52374. var properties = propertyPath.split(".");
  52375. for (var index = 0; index < properties.length - 1; index++) {
  52376. target = target[properties[index]];
  52377. }
  52378. return target;
  52379. };
  52380. /** @hidden */
  52381. ActionManager.prototype._getProperty = function (propertyPath) {
  52382. var properties = propertyPath.split(".");
  52383. return properties[properties.length - 1];
  52384. };
  52385. /**
  52386. * Serialize this manager to a JSON object
  52387. * @param name defines the property name to store this manager
  52388. * @returns a JSON representation of this manager
  52389. */
  52390. ActionManager.prototype.serialize = function (name) {
  52391. var root = {
  52392. children: new Array(),
  52393. name: name,
  52394. type: 3,
  52395. properties: new Array() // Empty for root but required
  52396. };
  52397. for (var i = 0; i < this.actions.length; i++) {
  52398. var triggerObject = {
  52399. type: 0,
  52400. children: new Array(),
  52401. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52402. properties: new Array()
  52403. };
  52404. var triggerOptions = this.actions[i].triggerOptions;
  52405. if (triggerOptions && typeof triggerOptions !== "number") {
  52406. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52407. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52408. }
  52409. else {
  52410. var parameter = {};
  52411. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52412. if (triggerOptions.parameter.mesh) {
  52413. parameter._meshId = triggerOptions.parameter.mesh.id;
  52414. }
  52415. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52416. }
  52417. }
  52418. // Serialize child action, recursively
  52419. this.actions[i].serialize(triggerObject);
  52420. // Add serialized trigger
  52421. root.children.push(triggerObject);
  52422. }
  52423. return root;
  52424. };
  52425. /**
  52426. * Creates a new ActionManager from a JSON data
  52427. * @param parsedActions defines the JSON data to read from
  52428. * @param object defines the hosting mesh
  52429. * @param scene defines the hosting scene
  52430. */
  52431. ActionManager.Parse = function (parsedActions, object, scene) {
  52432. var actionManager = new ActionManager(scene);
  52433. if (object === null)
  52434. scene.actionManager = actionManager;
  52435. else
  52436. object.actionManager = actionManager;
  52437. // instanciate a new object
  52438. var instanciate = function (name, params) {
  52439. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52440. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52441. newInstance.constructor.apply(newInstance, params);
  52442. return newInstance;
  52443. };
  52444. var parseParameter = function (name, value, target, propertyPath) {
  52445. if (propertyPath === null) {
  52446. // String, boolean or float
  52447. var floatValue = parseFloat(value);
  52448. if (value === "true" || value === "false")
  52449. return value === "true";
  52450. else
  52451. return isNaN(floatValue) ? value : floatValue;
  52452. }
  52453. var effectiveTarget = propertyPath.split(".");
  52454. var values = value.split(",");
  52455. // Get effective Target
  52456. for (var i = 0; i < effectiveTarget.length; i++) {
  52457. target = target[effectiveTarget[i]];
  52458. }
  52459. // Return appropriate value with its type
  52460. if (typeof (target) === "boolean")
  52461. return values[0] === "true";
  52462. if (typeof (target) === "string")
  52463. return values[0];
  52464. // Parameters with multiple values such as Vector3 etc.
  52465. var split = new Array();
  52466. for (var i = 0; i < values.length; i++)
  52467. split.push(parseFloat(values[i]));
  52468. if (target instanceof BABYLON.Vector3)
  52469. return BABYLON.Vector3.FromArray(split);
  52470. if (target instanceof BABYLON.Vector4)
  52471. return BABYLON.Vector4.FromArray(split);
  52472. if (target instanceof BABYLON.Color3)
  52473. return BABYLON.Color3.FromArray(split);
  52474. if (target instanceof BABYLON.Color4)
  52475. return BABYLON.Color4.FromArray(split);
  52476. return parseFloat(values[0]);
  52477. };
  52478. // traverse graph per trigger
  52479. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52480. if (combineArray === void 0) { combineArray = null; }
  52481. if (parsedAction.detached)
  52482. return;
  52483. var parameters = new Array();
  52484. var target = null;
  52485. var propertyPath = null;
  52486. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52487. // Parameters
  52488. if (parsedAction.type === 2)
  52489. parameters.push(actionManager);
  52490. else
  52491. parameters.push(trigger);
  52492. if (combine) {
  52493. var actions = new Array();
  52494. for (var j = 0; j < parsedAction.combine.length; j++) {
  52495. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52496. }
  52497. parameters.push(actions);
  52498. }
  52499. else {
  52500. for (var i = 0; i < parsedAction.properties.length; i++) {
  52501. var value = parsedAction.properties[i].value;
  52502. var name = parsedAction.properties[i].name;
  52503. var targetType = parsedAction.properties[i].targetType;
  52504. if (name === "target")
  52505. if (targetType !== null && targetType === "SceneProperties")
  52506. value = target = scene;
  52507. else
  52508. value = target = scene.getNodeByName(value);
  52509. else if (name === "parent")
  52510. value = scene.getNodeByName(value);
  52511. else if (name === "sound")
  52512. value = scene.getSoundByName(value);
  52513. else if (name !== "propertyPath") {
  52514. if (parsedAction.type === 2 && name === "operator")
  52515. value = BABYLON.ValueCondition[value];
  52516. else
  52517. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52518. }
  52519. else {
  52520. propertyPath = value;
  52521. }
  52522. parameters.push(value);
  52523. }
  52524. }
  52525. if (combineArray === null) {
  52526. parameters.push(condition);
  52527. }
  52528. else {
  52529. parameters.push(null);
  52530. }
  52531. // If interpolate value action
  52532. if (parsedAction.name === "InterpolateValueAction") {
  52533. var param = parameters[parameters.length - 2];
  52534. parameters[parameters.length - 1] = param;
  52535. parameters[parameters.length - 2] = condition;
  52536. }
  52537. // Action or condition(s) and not CombineAction
  52538. var newAction = instanciate(parsedAction.name, parameters);
  52539. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52540. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52541. if (action)
  52542. action.then(nothing);
  52543. else
  52544. actionManager.registerAction(nothing);
  52545. action = nothing;
  52546. }
  52547. if (combineArray === null) {
  52548. if (newAction instanceof BABYLON.Condition) {
  52549. condition = newAction;
  52550. newAction = action;
  52551. }
  52552. else {
  52553. condition = null;
  52554. if (action)
  52555. action.then(newAction);
  52556. else
  52557. actionManager.registerAction(newAction);
  52558. }
  52559. }
  52560. else {
  52561. combineArray.push(newAction);
  52562. }
  52563. for (var i = 0; i < parsedAction.children.length; i++)
  52564. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52565. };
  52566. // triggers
  52567. for (var i = 0; i < parsedActions.children.length; i++) {
  52568. var triggerParams;
  52569. var trigger = parsedActions.children[i];
  52570. if (trigger.properties.length > 0) {
  52571. var param = trigger.properties[0].value;
  52572. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52573. if (value._meshId) {
  52574. value.mesh = scene.getMeshByID(value._meshId);
  52575. }
  52576. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52577. }
  52578. else
  52579. triggerParams = ActionManager[trigger.name];
  52580. for (var j = 0; j < trigger.children.length; j++) {
  52581. if (!trigger.detached)
  52582. traverse(trigger.children[j], triggerParams, null, null);
  52583. }
  52584. }
  52585. };
  52586. /**
  52587. * Get a trigger name by index
  52588. * @param trigger defines the trigger index
  52589. * @returns a trigger name
  52590. */
  52591. ActionManager.GetTriggerName = function (trigger) {
  52592. switch (trigger) {
  52593. case 0: return "NothingTrigger";
  52594. case 1: return "OnPickTrigger";
  52595. case 2: return "OnLeftPickTrigger";
  52596. case 3: return "OnRightPickTrigger";
  52597. case 4: return "OnCenterPickTrigger";
  52598. case 5: return "OnPickDownTrigger";
  52599. case 6: return "OnPickUpTrigger";
  52600. case 7: return "OnLongPressTrigger";
  52601. case 8: return "OnPointerOverTrigger";
  52602. case 9: return "OnPointerOutTrigger";
  52603. case 10: return "OnEveryFrameTrigger";
  52604. case 11: return "OnIntersectionEnterTrigger";
  52605. case 12: return "OnIntersectionExitTrigger";
  52606. case 13: return "OnKeyDownTrigger";
  52607. case 14: return "OnKeyUpTrigger";
  52608. case 15: return "OnPickOutTrigger";
  52609. default: return "";
  52610. }
  52611. };
  52612. // Statics
  52613. ActionManager._NothingTrigger = 0;
  52614. ActionManager._OnPickTrigger = 1;
  52615. ActionManager._OnLeftPickTrigger = 2;
  52616. ActionManager._OnRightPickTrigger = 3;
  52617. ActionManager._OnCenterPickTrigger = 4;
  52618. ActionManager._OnPickDownTrigger = 5;
  52619. ActionManager._OnDoublePickTrigger = 6;
  52620. ActionManager._OnPickUpTrigger = 7;
  52621. ActionManager._OnLongPressTrigger = 8;
  52622. ActionManager._OnPointerOverTrigger = 9;
  52623. ActionManager._OnPointerOutTrigger = 10;
  52624. ActionManager._OnEveryFrameTrigger = 11;
  52625. ActionManager._OnIntersectionEnterTrigger = 12;
  52626. ActionManager._OnIntersectionExitTrigger = 13;
  52627. ActionManager._OnKeyDownTrigger = 14;
  52628. ActionManager._OnKeyUpTrigger = 15;
  52629. ActionManager._OnPickOutTrigger = 16;
  52630. /** Gets the list of active triggers */
  52631. ActionManager.Triggers = {};
  52632. return ActionManager;
  52633. }());
  52634. BABYLON.ActionManager = ActionManager;
  52635. })(BABYLON || (BABYLON = {}));
  52636. //# sourceMappingURL=babylon.actionManager.js.map
  52637. var BABYLON;
  52638. (function (BABYLON) {
  52639. var InterpolateValueAction = /** @class */ (function (_super) {
  52640. __extends(InterpolateValueAction, _super);
  52641. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52642. if (duration === void 0) { duration = 1000; }
  52643. var _this = _super.call(this, triggerOptions, condition) || this;
  52644. _this.propertyPath = propertyPath;
  52645. _this.value = value;
  52646. _this.duration = duration;
  52647. _this.stopOtherAnimations = stopOtherAnimations;
  52648. _this.onInterpolationDone = onInterpolationDone;
  52649. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52650. _this._target = _this._effectiveTarget = target;
  52651. return _this;
  52652. }
  52653. InterpolateValueAction.prototype._prepare = function () {
  52654. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52655. this._property = this._getProperty(this.propertyPath);
  52656. };
  52657. InterpolateValueAction.prototype.execute = function () {
  52658. var _this = this;
  52659. var scene = this._actionManager.getScene();
  52660. var keys = [
  52661. {
  52662. frame: 0,
  52663. value: this._effectiveTarget[this._property]
  52664. }, {
  52665. frame: 100,
  52666. value: this.value
  52667. }
  52668. ];
  52669. var dataType;
  52670. if (typeof this.value === "number") {
  52671. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52672. }
  52673. else if (this.value instanceof BABYLON.Color3) {
  52674. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52675. }
  52676. else if (this.value instanceof BABYLON.Vector3) {
  52677. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52678. }
  52679. else if (this.value instanceof BABYLON.Matrix) {
  52680. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52681. }
  52682. else if (this.value instanceof BABYLON.Quaternion) {
  52683. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52684. }
  52685. else {
  52686. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52687. return;
  52688. }
  52689. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52690. animation.setKeys(keys);
  52691. if (this.stopOtherAnimations) {
  52692. scene.stopAnimation(this._effectiveTarget);
  52693. }
  52694. var wrapper = function () {
  52695. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52696. if (_this.onInterpolationDone) {
  52697. _this.onInterpolationDone();
  52698. }
  52699. };
  52700. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52701. };
  52702. InterpolateValueAction.prototype.serialize = function (parent) {
  52703. return _super.prototype._serialize.call(this, {
  52704. name: "InterpolateValueAction",
  52705. properties: [
  52706. BABYLON.Action._GetTargetProperty(this._target),
  52707. { name: "propertyPath", value: this.propertyPath },
  52708. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52709. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52710. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52711. ]
  52712. }, parent);
  52713. };
  52714. return InterpolateValueAction;
  52715. }(BABYLON.Action));
  52716. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52717. })(BABYLON || (BABYLON = {}));
  52718. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52719. var BABYLON;
  52720. (function (BABYLON) {
  52721. var SwitchBooleanAction = /** @class */ (function (_super) {
  52722. __extends(SwitchBooleanAction, _super);
  52723. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52724. var _this = _super.call(this, triggerOptions, condition) || this;
  52725. _this.propertyPath = propertyPath;
  52726. _this._target = _this._effectiveTarget = target;
  52727. return _this;
  52728. }
  52729. SwitchBooleanAction.prototype._prepare = function () {
  52730. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52731. this._property = this._getProperty(this.propertyPath);
  52732. };
  52733. SwitchBooleanAction.prototype.execute = function () {
  52734. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52735. };
  52736. SwitchBooleanAction.prototype.serialize = function (parent) {
  52737. return _super.prototype._serialize.call(this, {
  52738. name: "SwitchBooleanAction",
  52739. properties: [
  52740. BABYLON.Action._GetTargetProperty(this._target),
  52741. { name: "propertyPath", value: this.propertyPath }
  52742. ]
  52743. }, parent);
  52744. };
  52745. return SwitchBooleanAction;
  52746. }(BABYLON.Action));
  52747. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52748. var SetStateAction = /** @class */ (function (_super) {
  52749. __extends(SetStateAction, _super);
  52750. function SetStateAction(triggerOptions, target, value, condition) {
  52751. var _this = _super.call(this, triggerOptions, condition) || this;
  52752. _this.value = value;
  52753. _this._target = target;
  52754. return _this;
  52755. }
  52756. SetStateAction.prototype.execute = function () {
  52757. this._target.state = this.value;
  52758. };
  52759. SetStateAction.prototype.serialize = function (parent) {
  52760. return _super.prototype._serialize.call(this, {
  52761. name: "SetStateAction",
  52762. properties: [
  52763. BABYLON.Action._GetTargetProperty(this._target),
  52764. { name: "value", value: this.value }
  52765. ]
  52766. }, parent);
  52767. };
  52768. return SetStateAction;
  52769. }(BABYLON.Action));
  52770. BABYLON.SetStateAction = SetStateAction;
  52771. var SetValueAction = /** @class */ (function (_super) {
  52772. __extends(SetValueAction, _super);
  52773. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52774. var _this = _super.call(this, triggerOptions, condition) || this;
  52775. _this.propertyPath = propertyPath;
  52776. _this.value = value;
  52777. _this._target = _this._effectiveTarget = target;
  52778. return _this;
  52779. }
  52780. SetValueAction.prototype._prepare = function () {
  52781. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52782. this._property = this._getProperty(this.propertyPath);
  52783. };
  52784. SetValueAction.prototype.execute = function () {
  52785. this._effectiveTarget[this._property] = this.value;
  52786. if (this._target.markAsDirty) {
  52787. this._target.markAsDirty(this._property);
  52788. }
  52789. };
  52790. SetValueAction.prototype.serialize = function (parent) {
  52791. return _super.prototype._serialize.call(this, {
  52792. name: "SetValueAction",
  52793. properties: [
  52794. BABYLON.Action._GetTargetProperty(this._target),
  52795. { name: "propertyPath", value: this.propertyPath },
  52796. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52797. ]
  52798. }, parent);
  52799. };
  52800. return SetValueAction;
  52801. }(BABYLON.Action));
  52802. BABYLON.SetValueAction = SetValueAction;
  52803. var IncrementValueAction = /** @class */ (function (_super) {
  52804. __extends(IncrementValueAction, _super);
  52805. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52806. var _this = _super.call(this, triggerOptions, condition) || this;
  52807. _this.propertyPath = propertyPath;
  52808. _this.value = value;
  52809. _this._target = _this._effectiveTarget = target;
  52810. return _this;
  52811. }
  52812. IncrementValueAction.prototype._prepare = function () {
  52813. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52814. this._property = this._getProperty(this.propertyPath);
  52815. if (typeof this._effectiveTarget[this._property] !== "number") {
  52816. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52817. }
  52818. };
  52819. IncrementValueAction.prototype.execute = function () {
  52820. this._effectiveTarget[this._property] += this.value;
  52821. if (this._target.markAsDirty) {
  52822. this._target.markAsDirty(this._property);
  52823. }
  52824. };
  52825. IncrementValueAction.prototype.serialize = function (parent) {
  52826. return _super.prototype._serialize.call(this, {
  52827. name: "IncrementValueAction",
  52828. properties: [
  52829. BABYLON.Action._GetTargetProperty(this._target),
  52830. { name: "propertyPath", value: this.propertyPath },
  52831. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52832. ]
  52833. }, parent);
  52834. };
  52835. return IncrementValueAction;
  52836. }(BABYLON.Action));
  52837. BABYLON.IncrementValueAction = IncrementValueAction;
  52838. var PlayAnimationAction = /** @class */ (function (_super) {
  52839. __extends(PlayAnimationAction, _super);
  52840. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52841. var _this = _super.call(this, triggerOptions, condition) || this;
  52842. _this.from = from;
  52843. _this.to = to;
  52844. _this.loop = loop;
  52845. _this._target = target;
  52846. return _this;
  52847. }
  52848. PlayAnimationAction.prototype._prepare = function () {
  52849. };
  52850. PlayAnimationAction.prototype.execute = function () {
  52851. var scene = this._actionManager.getScene();
  52852. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52853. };
  52854. PlayAnimationAction.prototype.serialize = function (parent) {
  52855. return _super.prototype._serialize.call(this, {
  52856. name: "PlayAnimationAction",
  52857. properties: [
  52858. BABYLON.Action._GetTargetProperty(this._target),
  52859. { name: "from", value: String(this.from) },
  52860. { name: "to", value: String(this.to) },
  52861. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52862. ]
  52863. }, parent);
  52864. };
  52865. return PlayAnimationAction;
  52866. }(BABYLON.Action));
  52867. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52868. var StopAnimationAction = /** @class */ (function (_super) {
  52869. __extends(StopAnimationAction, _super);
  52870. function StopAnimationAction(triggerOptions, target, condition) {
  52871. var _this = _super.call(this, triggerOptions, condition) || this;
  52872. _this._target = target;
  52873. return _this;
  52874. }
  52875. StopAnimationAction.prototype._prepare = function () {
  52876. };
  52877. StopAnimationAction.prototype.execute = function () {
  52878. var scene = this._actionManager.getScene();
  52879. scene.stopAnimation(this._target);
  52880. };
  52881. StopAnimationAction.prototype.serialize = function (parent) {
  52882. return _super.prototype._serialize.call(this, {
  52883. name: "StopAnimationAction",
  52884. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52885. }, parent);
  52886. };
  52887. return StopAnimationAction;
  52888. }(BABYLON.Action));
  52889. BABYLON.StopAnimationAction = StopAnimationAction;
  52890. var DoNothingAction = /** @class */ (function (_super) {
  52891. __extends(DoNothingAction, _super);
  52892. function DoNothingAction(triggerOptions, condition) {
  52893. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52894. return _super.call(this, triggerOptions, condition) || this;
  52895. }
  52896. DoNothingAction.prototype.execute = function () {
  52897. };
  52898. DoNothingAction.prototype.serialize = function (parent) {
  52899. return _super.prototype._serialize.call(this, {
  52900. name: "DoNothingAction",
  52901. properties: []
  52902. }, parent);
  52903. };
  52904. return DoNothingAction;
  52905. }(BABYLON.Action));
  52906. BABYLON.DoNothingAction = DoNothingAction;
  52907. var CombineAction = /** @class */ (function (_super) {
  52908. __extends(CombineAction, _super);
  52909. function CombineAction(triggerOptions, children, condition) {
  52910. var _this = _super.call(this, triggerOptions, condition) || this;
  52911. _this.children = children;
  52912. return _this;
  52913. }
  52914. CombineAction.prototype._prepare = function () {
  52915. for (var index = 0; index < this.children.length; index++) {
  52916. this.children[index]._actionManager = this._actionManager;
  52917. this.children[index]._prepare();
  52918. }
  52919. };
  52920. CombineAction.prototype.execute = function (evt) {
  52921. for (var index = 0; index < this.children.length; index++) {
  52922. this.children[index].execute(evt);
  52923. }
  52924. };
  52925. CombineAction.prototype.serialize = function (parent) {
  52926. var serializationObject = _super.prototype._serialize.call(this, {
  52927. name: "CombineAction",
  52928. properties: [],
  52929. combine: []
  52930. }, parent);
  52931. for (var i = 0; i < this.children.length; i++) {
  52932. serializationObject.combine.push(this.children[i].serialize(null));
  52933. }
  52934. return serializationObject;
  52935. };
  52936. return CombineAction;
  52937. }(BABYLON.Action));
  52938. BABYLON.CombineAction = CombineAction;
  52939. var ExecuteCodeAction = /** @class */ (function (_super) {
  52940. __extends(ExecuteCodeAction, _super);
  52941. function ExecuteCodeAction(triggerOptions, func, condition) {
  52942. var _this = _super.call(this, triggerOptions, condition) || this;
  52943. _this.func = func;
  52944. return _this;
  52945. }
  52946. ExecuteCodeAction.prototype.execute = function (evt) {
  52947. this.func(evt);
  52948. };
  52949. return ExecuteCodeAction;
  52950. }(BABYLON.Action));
  52951. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52952. var SetParentAction = /** @class */ (function (_super) {
  52953. __extends(SetParentAction, _super);
  52954. function SetParentAction(triggerOptions, target, parent, condition) {
  52955. var _this = _super.call(this, triggerOptions, condition) || this;
  52956. _this._target = target;
  52957. _this._parent = parent;
  52958. return _this;
  52959. }
  52960. SetParentAction.prototype._prepare = function () {
  52961. };
  52962. SetParentAction.prototype.execute = function () {
  52963. if (this._target.parent === this._parent) {
  52964. return;
  52965. }
  52966. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52967. invertParentWorldMatrix.invert();
  52968. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52969. this._target.parent = this._parent;
  52970. };
  52971. SetParentAction.prototype.serialize = function (parent) {
  52972. return _super.prototype._serialize.call(this, {
  52973. name: "SetParentAction",
  52974. properties: [
  52975. BABYLON.Action._GetTargetProperty(this._target),
  52976. BABYLON.Action._GetTargetProperty(this._parent),
  52977. ]
  52978. }, parent);
  52979. };
  52980. return SetParentAction;
  52981. }(BABYLON.Action));
  52982. BABYLON.SetParentAction = SetParentAction;
  52983. var PlaySoundAction = /** @class */ (function (_super) {
  52984. __extends(PlaySoundAction, _super);
  52985. function PlaySoundAction(triggerOptions, sound, condition) {
  52986. var _this = _super.call(this, triggerOptions, condition) || this;
  52987. _this._sound = sound;
  52988. return _this;
  52989. }
  52990. PlaySoundAction.prototype._prepare = function () {
  52991. };
  52992. PlaySoundAction.prototype.execute = function () {
  52993. if (this._sound !== undefined)
  52994. this._sound.play();
  52995. };
  52996. PlaySoundAction.prototype.serialize = function (parent) {
  52997. return _super.prototype._serialize.call(this, {
  52998. name: "PlaySoundAction",
  52999. properties: [{ name: "sound", value: this._sound.name }]
  53000. }, parent);
  53001. };
  53002. return PlaySoundAction;
  53003. }(BABYLON.Action));
  53004. BABYLON.PlaySoundAction = PlaySoundAction;
  53005. var StopSoundAction = /** @class */ (function (_super) {
  53006. __extends(StopSoundAction, _super);
  53007. function StopSoundAction(triggerOptions, sound, condition) {
  53008. var _this = _super.call(this, triggerOptions, condition) || this;
  53009. _this._sound = sound;
  53010. return _this;
  53011. }
  53012. StopSoundAction.prototype._prepare = function () {
  53013. };
  53014. StopSoundAction.prototype.execute = function () {
  53015. if (this._sound !== undefined)
  53016. this._sound.stop();
  53017. };
  53018. StopSoundAction.prototype.serialize = function (parent) {
  53019. return _super.prototype._serialize.call(this, {
  53020. name: "StopSoundAction",
  53021. properties: [{ name: "sound", value: this._sound.name }]
  53022. }, parent);
  53023. };
  53024. return StopSoundAction;
  53025. }(BABYLON.Action));
  53026. BABYLON.StopSoundAction = StopSoundAction;
  53027. })(BABYLON || (BABYLON = {}));
  53028. //# sourceMappingURL=babylon.directActions.js.map
  53029. var BABYLON;
  53030. (function (BABYLON) {
  53031. var SpriteManager = /** @class */ (function () {
  53032. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53033. if (epsilon === void 0) { epsilon = 0.01; }
  53034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53035. this.name = name;
  53036. this.sprites = new Array();
  53037. this.renderingGroupId = 0;
  53038. this.layerMask = 0x0FFFFFFF;
  53039. this.fogEnabled = true;
  53040. this.isPickable = false;
  53041. /**
  53042. * An event triggered when the manager is disposed.
  53043. */
  53044. this.onDisposeObservable = new BABYLON.Observable();
  53045. this._vertexBuffers = {};
  53046. this._capacity = capacity;
  53047. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53048. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53049. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53050. if (cellSize.width && cellSize.height) {
  53051. this.cellWidth = cellSize.width;
  53052. this.cellHeight = cellSize.height;
  53053. }
  53054. else if (cellSize !== undefined) {
  53055. this.cellWidth = cellSize;
  53056. this.cellHeight = cellSize;
  53057. }
  53058. else {
  53059. return;
  53060. }
  53061. this._epsilon = epsilon;
  53062. this._scene = scene;
  53063. this._scene.spriteManagers.push(this);
  53064. var indices = [];
  53065. var index = 0;
  53066. for (var count = 0; count < capacity; count++) {
  53067. indices.push(index);
  53068. indices.push(index + 1);
  53069. indices.push(index + 2);
  53070. indices.push(index);
  53071. indices.push(index + 2);
  53072. indices.push(index + 3);
  53073. index += 4;
  53074. }
  53075. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53076. // VBO
  53077. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53078. this._vertexData = new Float32Array(capacity * 16 * 4);
  53079. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53080. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53081. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53082. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53083. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53084. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53085. this._vertexBuffers["options"] = options;
  53086. this._vertexBuffers["cellInfo"] = cellInfo;
  53087. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53088. // Effects
  53089. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53090. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53091. }
  53092. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53093. set: function (callback) {
  53094. if (this._onDisposeObserver) {
  53095. this.onDisposeObservable.remove(this._onDisposeObserver);
  53096. }
  53097. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53098. },
  53099. enumerable: true,
  53100. configurable: true
  53101. });
  53102. Object.defineProperty(SpriteManager.prototype, "texture", {
  53103. get: function () {
  53104. return this._spriteTexture;
  53105. },
  53106. set: function (value) {
  53107. this._spriteTexture = value;
  53108. },
  53109. enumerable: true,
  53110. configurable: true
  53111. });
  53112. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53113. var arrayOffset = index * 16;
  53114. if (offsetX === 0)
  53115. offsetX = this._epsilon;
  53116. else if (offsetX === 1)
  53117. offsetX = 1 - this._epsilon;
  53118. if (offsetY === 0)
  53119. offsetY = this._epsilon;
  53120. else if (offsetY === 1)
  53121. offsetY = 1 - this._epsilon;
  53122. this._vertexData[arrayOffset] = sprite.position.x;
  53123. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53124. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53125. this._vertexData[arrayOffset + 3] = sprite.angle;
  53126. this._vertexData[arrayOffset + 4] = sprite.width;
  53127. this._vertexData[arrayOffset + 5] = sprite.height;
  53128. this._vertexData[arrayOffset + 6] = offsetX;
  53129. this._vertexData[arrayOffset + 7] = offsetY;
  53130. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53131. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53132. var offset = (sprite.cellIndex / rowSize) >> 0;
  53133. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53134. this._vertexData[arrayOffset + 11] = offset;
  53135. // Color
  53136. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53137. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53138. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53139. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53140. };
  53141. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53142. var count = Math.min(this._capacity, this.sprites.length);
  53143. var min = BABYLON.Vector3.Zero();
  53144. var max = BABYLON.Vector3.Zero();
  53145. var distance = Number.MAX_VALUE;
  53146. var currentSprite = null;
  53147. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53148. var cameraView = camera.getViewMatrix();
  53149. for (var index = 0; index < count; index++) {
  53150. var sprite = this.sprites[index];
  53151. if (!sprite) {
  53152. continue;
  53153. }
  53154. if (predicate) {
  53155. if (!predicate(sprite)) {
  53156. continue;
  53157. }
  53158. }
  53159. else if (!sprite.isPickable) {
  53160. continue;
  53161. }
  53162. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53163. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53164. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53165. if (ray.intersectsBoxMinMax(min, max)) {
  53166. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53167. if (distance > currentDistance) {
  53168. distance = currentDistance;
  53169. currentSprite = sprite;
  53170. if (fastCheck) {
  53171. break;
  53172. }
  53173. }
  53174. }
  53175. }
  53176. if (currentSprite) {
  53177. var result = new BABYLON.PickingInfo();
  53178. result.hit = true;
  53179. result.pickedSprite = currentSprite;
  53180. result.distance = distance;
  53181. return result;
  53182. }
  53183. return null;
  53184. };
  53185. SpriteManager.prototype.render = function () {
  53186. // Check
  53187. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53188. return;
  53189. var engine = this._scene.getEngine();
  53190. var baseSize = this._spriteTexture.getBaseSize();
  53191. // Sprites
  53192. var deltaTime = engine.getDeltaTime();
  53193. var max = Math.min(this._capacity, this.sprites.length);
  53194. var rowSize = baseSize.width / this.cellWidth;
  53195. var offset = 0;
  53196. for (var index = 0; index < max; index++) {
  53197. var sprite = this.sprites[index];
  53198. if (!sprite || !sprite.isVisible) {
  53199. continue;
  53200. }
  53201. sprite._animate(deltaTime);
  53202. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53203. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53204. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53205. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53206. }
  53207. this._buffer.update(this._vertexData);
  53208. // Render
  53209. var effect = this._effectBase;
  53210. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53211. effect = this._effectFog;
  53212. }
  53213. engine.enableEffect(effect);
  53214. var viewMatrix = this._scene.getViewMatrix();
  53215. effect.setTexture("diffuseSampler", this._spriteTexture);
  53216. effect.setMatrix("view", viewMatrix);
  53217. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53218. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53219. // Fog
  53220. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53221. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53222. effect.setColor3("vFogColor", this._scene.fogColor);
  53223. }
  53224. // VBOs
  53225. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53226. // Draw order
  53227. engine.setDepthFunctionToLessOrEqual();
  53228. effect.setBool("alphaTest", true);
  53229. engine.setColorWrite(false);
  53230. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53231. engine.setColorWrite(true);
  53232. effect.setBool("alphaTest", false);
  53233. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53236. };
  53237. SpriteManager.prototype.dispose = function () {
  53238. if (this._buffer) {
  53239. this._buffer.dispose();
  53240. this._buffer = null;
  53241. }
  53242. if (this._indexBuffer) {
  53243. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53244. this._indexBuffer = null;
  53245. }
  53246. if (this._spriteTexture) {
  53247. this._spriteTexture.dispose();
  53248. this._spriteTexture = null;
  53249. }
  53250. // Remove from scene
  53251. var index = this._scene.spriteManagers.indexOf(this);
  53252. this._scene.spriteManagers.splice(index, 1);
  53253. // Callback
  53254. this.onDisposeObservable.notifyObservers(this);
  53255. this.onDisposeObservable.clear();
  53256. };
  53257. return SpriteManager;
  53258. }());
  53259. BABYLON.SpriteManager = SpriteManager;
  53260. })(BABYLON || (BABYLON = {}));
  53261. //# sourceMappingURL=babylon.spriteManager.js.map
  53262. var BABYLON;
  53263. (function (BABYLON) {
  53264. var Sprite = /** @class */ (function () {
  53265. function Sprite(name, manager) {
  53266. this.name = name;
  53267. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53268. this.width = 1.0;
  53269. this.height = 1.0;
  53270. this.angle = 0;
  53271. this.cellIndex = 0;
  53272. this.invertU = 0;
  53273. this.invertV = 0;
  53274. this.animations = new Array();
  53275. this.isPickable = false;
  53276. this._animationStarted = false;
  53277. this._loopAnimation = false;
  53278. this._fromIndex = 0;
  53279. this._toIndex = 0;
  53280. this._delay = 0;
  53281. this._direction = 1;
  53282. this._time = 0;
  53283. /**
  53284. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53285. */
  53286. this.isVisible = true;
  53287. this._manager = manager;
  53288. this._manager.sprites.push(this);
  53289. this.position = BABYLON.Vector3.Zero();
  53290. }
  53291. Object.defineProperty(Sprite.prototype, "size", {
  53292. get: function () {
  53293. return this.width;
  53294. },
  53295. set: function (value) {
  53296. this.width = value;
  53297. this.height = value;
  53298. },
  53299. enumerable: true,
  53300. configurable: true
  53301. });
  53302. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53303. this._fromIndex = from;
  53304. this._toIndex = to;
  53305. this._loopAnimation = loop;
  53306. this._delay = delay;
  53307. this._animationStarted = true;
  53308. this._direction = from < to ? 1 : -1;
  53309. this.cellIndex = from;
  53310. this._time = 0;
  53311. this._onAnimationEnd = onAnimationEnd;
  53312. };
  53313. Sprite.prototype.stopAnimation = function () {
  53314. this._animationStarted = false;
  53315. };
  53316. Sprite.prototype._animate = function (deltaTime) {
  53317. if (!this._animationStarted)
  53318. return;
  53319. this._time += deltaTime;
  53320. if (this._time > this._delay) {
  53321. this._time = this._time % this._delay;
  53322. this.cellIndex += this._direction;
  53323. if (this.cellIndex > this._toIndex) {
  53324. if (this._loopAnimation) {
  53325. this.cellIndex = this._fromIndex;
  53326. }
  53327. else {
  53328. this.cellIndex = this._toIndex;
  53329. this._animationStarted = false;
  53330. if (this._onAnimationEnd) {
  53331. this._onAnimationEnd();
  53332. }
  53333. if (this.disposeWhenFinishedAnimating) {
  53334. this.dispose();
  53335. }
  53336. }
  53337. }
  53338. }
  53339. };
  53340. Sprite.prototype.dispose = function () {
  53341. for (var i = 0; i < this._manager.sprites.length; i++) {
  53342. if (this._manager.sprites[i] == this) {
  53343. this._manager.sprites.splice(i, 1);
  53344. }
  53345. }
  53346. };
  53347. return Sprite;
  53348. }());
  53349. BABYLON.Sprite = Sprite;
  53350. })(BABYLON || (BABYLON = {}));
  53351. //# sourceMappingURL=babylon.sprite.js.map
  53352. var BABYLON;
  53353. (function (BABYLON) {
  53354. var IntersectionInfo = /** @class */ (function () {
  53355. function IntersectionInfo(bu, bv, distance) {
  53356. this.bu = bu;
  53357. this.bv = bv;
  53358. this.distance = distance;
  53359. this.faceId = 0;
  53360. this.subMeshId = 0;
  53361. }
  53362. return IntersectionInfo;
  53363. }());
  53364. BABYLON.IntersectionInfo = IntersectionInfo;
  53365. /**
  53366. * Information about the result of picking within a scene
  53367. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53368. */
  53369. var PickingInfo = /** @class */ (function () {
  53370. function PickingInfo() {
  53371. /**
  53372. * If the pick collided with an object
  53373. */
  53374. this.hit = false;
  53375. /**
  53376. * Distance away where the pick collided
  53377. */
  53378. this.distance = 0;
  53379. /**
  53380. * The location of pick collision
  53381. */
  53382. this.pickedPoint = null;
  53383. /**
  53384. * The mesh corrisponding the the pick collision
  53385. */
  53386. this.pickedMesh = null;
  53387. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53388. this.bu = 0;
  53389. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53390. this.bv = 0;
  53391. /** The id of the face on the mesh that was picked */
  53392. this.faceId = -1;
  53393. /** Id of the the submesh that was picked */
  53394. this.subMeshId = 0;
  53395. /** If a sprite was picked, this will be the sprite the pick collided with */
  53396. this.pickedSprite = null;
  53397. /**
  53398. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53399. */
  53400. this.originMesh = null;
  53401. /**
  53402. * The ray that was used to perform the picking.
  53403. */
  53404. this.ray = null;
  53405. }
  53406. /**
  53407. * Gets the normal corrispodning to the face the pick collided with
  53408. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53409. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53410. * @returns The normal corrispodning to the face the pick collided with
  53411. */
  53412. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53413. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53414. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53415. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53416. return null;
  53417. }
  53418. var indices = this.pickedMesh.getIndices();
  53419. if (!indices) {
  53420. return null;
  53421. }
  53422. var result;
  53423. if (useVerticesNormals) {
  53424. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53425. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53426. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53427. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53428. normal0 = normal0.scale(this.bu);
  53429. normal1 = normal1.scale(this.bv);
  53430. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53431. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53432. }
  53433. else {
  53434. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53435. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53436. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53437. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53438. var p1p2 = vertex1.subtract(vertex2);
  53439. var p3p2 = vertex3.subtract(vertex2);
  53440. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53441. }
  53442. if (useWorldCoordinates) {
  53443. var wm = this.pickedMesh.getWorldMatrix();
  53444. if (this.pickedMesh.nonUniformScaling) {
  53445. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53446. wm = BABYLON.Tmp.Matrix[0];
  53447. wm.setTranslationFromFloats(0, 0, 0);
  53448. wm.invert();
  53449. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53450. wm = BABYLON.Tmp.Matrix[1];
  53451. }
  53452. result = BABYLON.Vector3.TransformNormal(result, wm);
  53453. }
  53454. result.normalize();
  53455. return result;
  53456. };
  53457. /**
  53458. * Gets the texture coordinates of where the pick occured
  53459. * @returns the vector containing the coordnates of the texture
  53460. */
  53461. PickingInfo.prototype.getTextureCoordinates = function () {
  53462. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53463. return null;
  53464. }
  53465. var indices = this.pickedMesh.getIndices();
  53466. if (!indices) {
  53467. return null;
  53468. }
  53469. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53470. if (!uvs) {
  53471. return null;
  53472. }
  53473. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53474. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53475. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53476. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53477. uv1 = uv1.scale(this.bu);
  53478. uv2 = uv2.scale(this.bv);
  53479. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53480. };
  53481. return PickingInfo;
  53482. }());
  53483. BABYLON.PickingInfo = PickingInfo;
  53484. })(BABYLON || (BABYLON = {}));
  53485. //# sourceMappingURL=babylon.pickingInfo.js.map
  53486. var BABYLON;
  53487. (function (BABYLON) {
  53488. var Ray = /** @class */ (function () {
  53489. function Ray(origin, direction, length) {
  53490. if (length === void 0) { length = Number.MAX_VALUE; }
  53491. this.origin = origin;
  53492. this.direction = direction;
  53493. this.length = length;
  53494. }
  53495. // Methods
  53496. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53497. var d = 0.0;
  53498. var maxValue = Number.MAX_VALUE;
  53499. var inv;
  53500. var min;
  53501. var max;
  53502. var temp;
  53503. if (Math.abs(this.direction.x) < 0.0000001) {
  53504. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53505. return false;
  53506. }
  53507. }
  53508. else {
  53509. inv = 1.0 / this.direction.x;
  53510. min = (minimum.x - this.origin.x) * inv;
  53511. max = (maximum.x - this.origin.x) * inv;
  53512. if (max === -Infinity) {
  53513. max = Infinity;
  53514. }
  53515. if (min > max) {
  53516. temp = min;
  53517. min = max;
  53518. max = temp;
  53519. }
  53520. d = Math.max(min, d);
  53521. maxValue = Math.min(max, maxValue);
  53522. if (d > maxValue) {
  53523. return false;
  53524. }
  53525. }
  53526. if (Math.abs(this.direction.y) < 0.0000001) {
  53527. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53528. return false;
  53529. }
  53530. }
  53531. else {
  53532. inv = 1.0 / this.direction.y;
  53533. min = (minimum.y - this.origin.y) * inv;
  53534. max = (maximum.y - this.origin.y) * inv;
  53535. if (max === -Infinity) {
  53536. max = Infinity;
  53537. }
  53538. if (min > max) {
  53539. temp = min;
  53540. min = max;
  53541. max = temp;
  53542. }
  53543. d = Math.max(min, d);
  53544. maxValue = Math.min(max, maxValue);
  53545. if (d > maxValue) {
  53546. return false;
  53547. }
  53548. }
  53549. if (Math.abs(this.direction.z) < 0.0000001) {
  53550. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53551. return false;
  53552. }
  53553. }
  53554. else {
  53555. inv = 1.0 / this.direction.z;
  53556. min = (minimum.z - this.origin.z) * inv;
  53557. max = (maximum.z - this.origin.z) * inv;
  53558. if (max === -Infinity) {
  53559. max = Infinity;
  53560. }
  53561. if (min > max) {
  53562. temp = min;
  53563. min = max;
  53564. max = temp;
  53565. }
  53566. d = Math.max(min, d);
  53567. maxValue = Math.min(max, maxValue);
  53568. if (d > maxValue) {
  53569. return false;
  53570. }
  53571. }
  53572. return true;
  53573. };
  53574. Ray.prototype.intersectsBox = function (box) {
  53575. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53576. };
  53577. Ray.prototype.intersectsSphere = function (sphere) {
  53578. var x = sphere.center.x - this.origin.x;
  53579. var y = sphere.center.y - this.origin.y;
  53580. var z = sphere.center.z - this.origin.z;
  53581. var pyth = (x * x) + (y * y) + (z * z);
  53582. var rr = sphere.radius * sphere.radius;
  53583. if (pyth <= rr) {
  53584. return true;
  53585. }
  53586. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53587. if (dot < 0.0) {
  53588. return false;
  53589. }
  53590. var temp = pyth - (dot * dot);
  53591. return temp <= rr;
  53592. };
  53593. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53594. if (!this._edge1) {
  53595. this._edge1 = BABYLON.Vector3.Zero();
  53596. this._edge2 = BABYLON.Vector3.Zero();
  53597. this._pvec = BABYLON.Vector3.Zero();
  53598. this._tvec = BABYLON.Vector3.Zero();
  53599. this._qvec = BABYLON.Vector3.Zero();
  53600. }
  53601. vertex1.subtractToRef(vertex0, this._edge1);
  53602. vertex2.subtractToRef(vertex0, this._edge2);
  53603. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53604. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53605. if (det === 0) {
  53606. return null;
  53607. }
  53608. var invdet = 1 / det;
  53609. this.origin.subtractToRef(vertex0, this._tvec);
  53610. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53611. if (bu < 0 || bu > 1.0) {
  53612. return null;
  53613. }
  53614. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53615. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53616. if (bv < 0 || bu + bv > 1.0) {
  53617. return null;
  53618. }
  53619. //check if the distance is longer than the predefined length.
  53620. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53621. if (distance > this.length) {
  53622. return null;
  53623. }
  53624. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53625. };
  53626. Ray.prototype.intersectsPlane = function (plane) {
  53627. var distance;
  53628. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53629. if (Math.abs(result1) < 9.99999997475243E-07) {
  53630. return null;
  53631. }
  53632. else {
  53633. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53634. distance = (-plane.d - result2) / result1;
  53635. if (distance < 0.0) {
  53636. if (distance < -9.99999997475243E-07) {
  53637. return null;
  53638. }
  53639. else {
  53640. return 0;
  53641. }
  53642. }
  53643. return distance;
  53644. }
  53645. };
  53646. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53647. var tm = BABYLON.Tmp.Matrix[0];
  53648. mesh.getWorldMatrix().invertToRef(tm);
  53649. if (this._tmpRay) {
  53650. Ray.TransformToRef(this, tm, this._tmpRay);
  53651. }
  53652. else {
  53653. this._tmpRay = Ray.Transform(this, tm);
  53654. }
  53655. return mesh.intersects(this._tmpRay, fastCheck);
  53656. };
  53657. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53658. if (results) {
  53659. results.length = 0;
  53660. }
  53661. else {
  53662. results = [];
  53663. }
  53664. for (var i = 0; i < meshes.length; i++) {
  53665. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53666. if (pickInfo.hit) {
  53667. results.push(pickInfo);
  53668. }
  53669. }
  53670. results.sort(this._comparePickingInfo);
  53671. return results;
  53672. };
  53673. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53674. if (pickingInfoA.distance < pickingInfoB.distance) {
  53675. return -1;
  53676. }
  53677. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53678. return 1;
  53679. }
  53680. else {
  53681. return 0;
  53682. }
  53683. };
  53684. /**
  53685. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53686. * @param sega the first point of the segment to test the intersection against
  53687. * @param segb the second point of the segment to test the intersection against
  53688. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53689. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53690. */
  53691. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53692. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53693. var u = segb.subtract(sega);
  53694. var v = rsegb.subtract(this.origin);
  53695. var w = sega.subtract(this.origin);
  53696. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53697. var b = BABYLON.Vector3.Dot(u, v);
  53698. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53699. var d = BABYLON.Vector3.Dot(u, w);
  53700. var e = BABYLON.Vector3.Dot(v, w);
  53701. var D = a * c - b * b; // always >= 0
  53702. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53703. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53704. // compute the line parameters of the two closest points
  53705. if (D < Ray.smallnum) { // the lines are almost parallel
  53706. sN = 0.0; // force using point P0 on segment S1
  53707. sD = 1.0; // to prevent possible division by 0.0 later
  53708. tN = e;
  53709. tD = c;
  53710. }
  53711. else { // get the closest points on the infinite lines
  53712. sN = (b * e - c * d);
  53713. tN = (a * e - b * d);
  53714. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  53715. sN = 0.0;
  53716. tN = e;
  53717. tD = c;
  53718. }
  53719. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  53720. sN = sD;
  53721. tN = e + b;
  53722. tD = c;
  53723. }
  53724. }
  53725. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  53726. tN = 0.0;
  53727. // recompute sc for this edge
  53728. if (-d < 0.0) {
  53729. sN = 0.0;
  53730. }
  53731. else if (-d > a)
  53732. sN = sD;
  53733. else {
  53734. sN = -d;
  53735. sD = a;
  53736. }
  53737. }
  53738. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  53739. tN = tD;
  53740. // recompute sc for this edge
  53741. if ((-d + b) < 0.0) {
  53742. sN = 0;
  53743. }
  53744. else if ((-d + b) > a) {
  53745. sN = sD;
  53746. }
  53747. else {
  53748. sN = (-d + b);
  53749. sD = a;
  53750. }
  53751. }
  53752. // finally do the division to get sc and tc
  53753. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53754. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53755. // get the difference of the two closest points
  53756. var qtc = v.multiplyByFloats(tc, tc, tc);
  53757. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53758. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53759. if (isIntersected) {
  53760. return qtc.length();
  53761. }
  53762. return -1;
  53763. };
  53764. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53765. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53766. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53767. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53768. this.direction.normalize();
  53769. return this;
  53770. };
  53771. // Statics
  53772. Ray.Zero = function () {
  53773. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53774. };
  53775. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53776. var result = Ray.Zero();
  53777. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53778. };
  53779. /**
  53780. * 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
  53781. * transformed to the given world matrix.
  53782. * @param origin The origin point
  53783. * @param end The end point
  53784. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53785. */
  53786. Ray.CreateNewFromTo = function (origin, end, world) {
  53787. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53788. var direction = end.subtract(origin);
  53789. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53790. direction.normalize();
  53791. return Ray.Transform(new Ray(origin, direction, length), world);
  53792. };
  53793. Ray.Transform = function (ray, matrix) {
  53794. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53795. Ray.TransformToRef(ray, matrix, result);
  53796. return result;
  53797. };
  53798. Ray.TransformToRef = function (ray, matrix, result) {
  53799. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53800. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53801. result.length = ray.length;
  53802. var dir = result.direction;
  53803. var len = dir.length();
  53804. if (!(len === 0 || len === 1)) {
  53805. var num = 1.0 / len;
  53806. dir.x *= num;
  53807. dir.y *= num;
  53808. dir.z *= num;
  53809. result.length *= len;
  53810. }
  53811. };
  53812. Ray.smallnum = 0.00000001;
  53813. Ray.rayl = 10e8;
  53814. return Ray;
  53815. }());
  53816. BABYLON.Ray = Ray;
  53817. })(BABYLON || (BABYLON = {}));
  53818. //# sourceMappingURL=babylon.ray.js.map
  53819. var BABYLON;
  53820. (function (BABYLON) {
  53821. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53822. if (boxMin.x > sphereCenter.x + sphereRadius)
  53823. return false;
  53824. if (sphereCenter.x - sphereRadius > boxMax.x)
  53825. return false;
  53826. if (boxMin.y > sphereCenter.y + sphereRadius)
  53827. return false;
  53828. if (sphereCenter.y - sphereRadius > boxMax.y)
  53829. return false;
  53830. if (boxMin.z > sphereCenter.z + sphereRadius)
  53831. return false;
  53832. if (sphereCenter.z - sphereRadius > boxMax.z)
  53833. return false;
  53834. return true;
  53835. };
  53836. var getLowestRoot = (function () {
  53837. var result = { root: 0, found: false };
  53838. return function (a, b, c, maxR) {
  53839. result.root = 0;
  53840. result.found = false;
  53841. var determinant = b * b - 4.0 * a * c;
  53842. if (determinant < 0)
  53843. return result;
  53844. var sqrtD = Math.sqrt(determinant);
  53845. var r1 = (-b - sqrtD) / (2.0 * a);
  53846. var r2 = (-b + sqrtD) / (2.0 * a);
  53847. if (r1 > r2) {
  53848. var temp = r2;
  53849. r2 = r1;
  53850. r1 = temp;
  53851. }
  53852. if (r1 > 0 && r1 < maxR) {
  53853. result.root = r1;
  53854. result.found = true;
  53855. return result;
  53856. }
  53857. if (r2 > 0 && r2 < maxR) {
  53858. result.root = r2;
  53859. result.found = true;
  53860. return result;
  53861. }
  53862. return result;
  53863. };
  53864. })();
  53865. var Collider = /** @class */ (function () {
  53866. function Collider() {
  53867. this._collisionPoint = BABYLON.Vector3.Zero();
  53868. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53869. this._tempVector = BABYLON.Vector3.Zero();
  53870. this._tempVector2 = BABYLON.Vector3.Zero();
  53871. this._tempVector3 = BABYLON.Vector3.Zero();
  53872. this._tempVector4 = BABYLON.Vector3.Zero();
  53873. this._edge = BABYLON.Vector3.Zero();
  53874. this._baseToVertex = BABYLON.Vector3.Zero();
  53875. this._destinationPoint = BABYLON.Vector3.Zero();
  53876. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53877. this._displacementVector = BABYLON.Vector3.Zero();
  53878. this._radius = BABYLON.Vector3.One();
  53879. this._retry = 0;
  53880. this._basePointWorld = BABYLON.Vector3.Zero();
  53881. this._velocityWorld = BABYLON.Vector3.Zero();
  53882. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53883. this._collisionMask = -1;
  53884. }
  53885. Object.defineProperty(Collider.prototype, "collisionMask", {
  53886. get: function () {
  53887. return this._collisionMask;
  53888. },
  53889. set: function (mask) {
  53890. this._collisionMask = !isNaN(mask) ? mask : -1;
  53891. },
  53892. enumerable: true,
  53893. configurable: true
  53894. });
  53895. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53896. /**
  53897. * Gets the plane normal used to compute the sliding response (in local space)
  53898. */
  53899. get: function () {
  53900. return this._slidePlaneNormal;
  53901. },
  53902. enumerable: true,
  53903. configurable: true
  53904. });
  53905. // Methods
  53906. Collider.prototype._initialize = function (source, dir, e) {
  53907. this._velocity = dir;
  53908. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53909. this._basePoint = source;
  53910. source.multiplyToRef(this._radius, this._basePointWorld);
  53911. dir.multiplyToRef(this._radius, this._velocityWorld);
  53912. this._velocityWorldLength = this._velocityWorld.length();
  53913. this._epsilon = e;
  53914. this.collisionFound = false;
  53915. };
  53916. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53917. pa.subtractToRef(point, this._tempVector);
  53918. pb.subtractToRef(point, this._tempVector2);
  53919. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53920. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53921. if (d < 0)
  53922. return false;
  53923. pc.subtractToRef(point, this._tempVector3);
  53924. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53925. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53926. if (d < 0)
  53927. return false;
  53928. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53929. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53930. return d >= 0;
  53931. };
  53932. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53933. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53934. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53935. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53936. return false;
  53937. }
  53938. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53939. return false;
  53940. return true;
  53941. };
  53942. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53943. var t0;
  53944. var embeddedInPlane = false;
  53945. //defensive programming, actually not needed.
  53946. if (!trianglePlaneArray) {
  53947. trianglePlaneArray = [];
  53948. }
  53949. if (!trianglePlaneArray[faceIndex]) {
  53950. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53951. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53952. }
  53953. var trianglePlane = trianglePlaneArray[faceIndex];
  53954. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53955. return;
  53956. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53957. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53958. if (normalDotVelocity == 0) {
  53959. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53960. return;
  53961. embeddedInPlane = true;
  53962. t0 = 0;
  53963. }
  53964. else {
  53965. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53966. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53967. if (t0 > t1) {
  53968. var temp = t1;
  53969. t1 = t0;
  53970. t0 = temp;
  53971. }
  53972. if (t0 > 1.0 || t1 < 0.0)
  53973. return;
  53974. if (t0 < 0)
  53975. t0 = 0;
  53976. if (t0 > 1.0)
  53977. t0 = 1.0;
  53978. }
  53979. this._collisionPoint.copyFromFloats(0, 0, 0);
  53980. var found = false;
  53981. var t = 1.0;
  53982. if (!embeddedInPlane) {
  53983. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53984. this._velocity.scaleToRef(t0, this._tempVector);
  53985. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53986. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53987. found = true;
  53988. t = t0;
  53989. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53990. }
  53991. }
  53992. if (!found) {
  53993. var velocitySquaredLength = this._velocity.lengthSquared();
  53994. var a = velocitySquaredLength;
  53995. this._basePoint.subtractToRef(p1, this._tempVector);
  53996. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53997. var c = this._tempVector.lengthSquared() - 1.0;
  53998. var lowestRoot = getLowestRoot(a, b, c, t);
  53999. if (lowestRoot.found) {
  54000. t = lowestRoot.root;
  54001. found = true;
  54002. this._collisionPoint.copyFrom(p1);
  54003. }
  54004. this._basePoint.subtractToRef(p2, this._tempVector);
  54005. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54006. c = this._tempVector.lengthSquared() - 1.0;
  54007. lowestRoot = getLowestRoot(a, b, c, t);
  54008. if (lowestRoot.found) {
  54009. t = lowestRoot.root;
  54010. found = true;
  54011. this._collisionPoint.copyFrom(p2);
  54012. }
  54013. this._basePoint.subtractToRef(p3, this._tempVector);
  54014. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54015. c = this._tempVector.lengthSquared() - 1.0;
  54016. lowestRoot = getLowestRoot(a, b, c, t);
  54017. if (lowestRoot.found) {
  54018. t = lowestRoot.root;
  54019. found = true;
  54020. this._collisionPoint.copyFrom(p3);
  54021. }
  54022. p2.subtractToRef(p1, this._edge);
  54023. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54024. var edgeSquaredLength = this._edge.lengthSquared();
  54025. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54026. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54027. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54028. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54029. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54030. lowestRoot = getLowestRoot(a, b, c, t);
  54031. if (lowestRoot.found) {
  54032. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54033. if (f >= 0.0 && f <= 1.0) {
  54034. t = lowestRoot.root;
  54035. found = true;
  54036. this._edge.scaleInPlace(f);
  54037. p1.addToRef(this._edge, this._collisionPoint);
  54038. }
  54039. }
  54040. p3.subtractToRef(p2, this._edge);
  54041. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54042. edgeSquaredLength = this._edge.lengthSquared();
  54043. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54044. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54045. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54046. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54047. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54048. lowestRoot = getLowestRoot(a, b, c, t);
  54049. if (lowestRoot.found) {
  54050. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54051. if (f >= 0.0 && f <= 1.0) {
  54052. t = lowestRoot.root;
  54053. found = true;
  54054. this._edge.scaleInPlace(f);
  54055. p2.addToRef(this._edge, this._collisionPoint);
  54056. }
  54057. }
  54058. p1.subtractToRef(p3, this._edge);
  54059. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54060. edgeSquaredLength = this._edge.lengthSquared();
  54061. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54062. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54063. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54064. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54065. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54066. lowestRoot = getLowestRoot(a, b, c, t);
  54067. if (lowestRoot.found) {
  54068. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54069. if (f >= 0.0 && f <= 1.0) {
  54070. t = lowestRoot.root;
  54071. found = true;
  54072. this._edge.scaleInPlace(f);
  54073. p3.addToRef(this._edge, this._collisionPoint);
  54074. }
  54075. }
  54076. }
  54077. if (found) {
  54078. var distToCollision = t * this._velocity.length();
  54079. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54080. if (!this.intersectionPoint) {
  54081. this.intersectionPoint = this._collisionPoint.clone();
  54082. }
  54083. else {
  54084. this.intersectionPoint.copyFrom(this._collisionPoint);
  54085. }
  54086. this._nearestDistance = distToCollision;
  54087. this.collisionFound = true;
  54088. }
  54089. }
  54090. };
  54091. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54092. for (var i = indexStart; i < indexEnd; i += 3) {
  54093. var p1 = pts[indices[i] - decal];
  54094. var p2 = pts[indices[i + 1] - decal];
  54095. var p3 = pts[indices[i + 2] - decal];
  54096. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54097. }
  54098. };
  54099. Collider.prototype._getResponse = function (pos, vel) {
  54100. pos.addToRef(vel, this._destinationPoint);
  54101. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54102. this._basePoint.addToRef(vel, pos);
  54103. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54104. this._slidePlaneNormal.normalize();
  54105. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54106. pos.addInPlace(this._displacementVector);
  54107. this.intersectionPoint.addInPlace(this._displacementVector);
  54108. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54109. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54110. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54111. };
  54112. return Collider;
  54113. }());
  54114. BABYLON.Collider = Collider;
  54115. })(BABYLON || (BABYLON = {}));
  54116. //# sourceMappingURL=babylon.collider.js.map
  54117. var BABYLON;
  54118. (function (BABYLON) {
  54119. //WebWorker code will be inserted to this variable.
  54120. BABYLON.CollisionWorker = "";
  54121. /** Defines supported task for worker process */
  54122. var WorkerTaskType;
  54123. (function (WorkerTaskType) {
  54124. /** Initialization */
  54125. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54126. /** Update of geometry */
  54127. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54128. /** Evaluate collision */
  54129. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54130. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54131. /** Defines kind of replies returned by worker */
  54132. var WorkerReplyType;
  54133. (function (WorkerReplyType) {
  54134. /** Success */
  54135. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54136. /** Unkown error */
  54137. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54138. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54139. var CollisionCoordinatorWorker = /** @class */ (function () {
  54140. function CollisionCoordinatorWorker() {
  54141. var _this = this;
  54142. this._scaledPosition = BABYLON.Vector3.Zero();
  54143. this._scaledVelocity = BABYLON.Vector3.Zero();
  54144. this.onMeshUpdated = function (transformNode) {
  54145. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54146. };
  54147. this.onGeometryUpdated = function (geometry) {
  54148. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54149. };
  54150. this._afterRender = function () {
  54151. if (!_this._init)
  54152. return;
  54153. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54154. return;
  54155. }
  54156. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54157. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54158. if (_this._runningUpdated > 4) {
  54159. return;
  54160. }
  54161. ++_this._runningUpdated;
  54162. var payload = {
  54163. updatedMeshes: _this._addUpdateMeshesList,
  54164. updatedGeometries: _this._addUpdateGeometriesList,
  54165. removedGeometries: _this._toRemoveGeometryArray,
  54166. removedMeshes: _this._toRemoveMeshesArray
  54167. };
  54168. var message = {
  54169. payload: payload,
  54170. taskType: WorkerTaskType.UPDATE
  54171. };
  54172. var serializable = [];
  54173. for (var id in payload.updatedGeometries) {
  54174. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54175. //prepare transferables
  54176. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54177. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54178. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54179. }
  54180. }
  54181. _this._worker.postMessage(message, serializable);
  54182. _this._addUpdateMeshesList = {};
  54183. _this._addUpdateGeometriesList = {};
  54184. _this._toRemoveGeometryArray = [];
  54185. _this._toRemoveMeshesArray = [];
  54186. };
  54187. this._onMessageFromWorker = function (e) {
  54188. var returnData = e.data;
  54189. if (returnData.error != WorkerReplyType.SUCCESS) {
  54190. //TODO what errors can be returned from the worker?
  54191. BABYLON.Tools.Warn("error returned from worker!");
  54192. return;
  54193. }
  54194. switch (returnData.taskType) {
  54195. case WorkerTaskType.INIT:
  54196. _this._init = true;
  54197. //Update the worked with ALL of the scene's current state
  54198. _this._scene.meshes.forEach(function (mesh) {
  54199. _this.onMeshAdded(mesh);
  54200. });
  54201. _this._scene.getGeometries().forEach(function (geometry) {
  54202. _this.onGeometryAdded(geometry);
  54203. });
  54204. break;
  54205. case WorkerTaskType.UPDATE:
  54206. _this._runningUpdated--;
  54207. break;
  54208. case WorkerTaskType.COLLIDE:
  54209. var returnPayload = returnData.payload;
  54210. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54211. return;
  54212. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54213. if (callback) {
  54214. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54215. if (mesh) {
  54216. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54217. }
  54218. }
  54219. //cleanup
  54220. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54221. break;
  54222. }
  54223. };
  54224. this._collisionsCallbackArray = [];
  54225. this._init = false;
  54226. this._runningUpdated = 0;
  54227. this._addUpdateMeshesList = {};
  54228. this._addUpdateGeometriesList = {};
  54229. this._toRemoveGeometryArray = [];
  54230. this._toRemoveMeshesArray = [];
  54231. }
  54232. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54233. if (!this._init)
  54234. return;
  54235. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54236. return;
  54237. position.divideToRef(collider._radius, this._scaledPosition);
  54238. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54239. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54240. var payload = {
  54241. collider: {
  54242. position: this._scaledPosition.asArray(),
  54243. velocity: this._scaledVelocity.asArray(),
  54244. radius: collider._radius.asArray()
  54245. },
  54246. collisionId: collisionIndex,
  54247. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54248. maximumRetry: maximumRetry
  54249. };
  54250. var message = {
  54251. payload: payload,
  54252. taskType: WorkerTaskType.COLLIDE
  54253. };
  54254. this._worker.postMessage(message);
  54255. };
  54256. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54257. this._scene = scene;
  54258. this._scene.registerAfterRender(this._afterRender);
  54259. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54260. this._worker = new Worker(workerUrl);
  54261. this._worker.onmessage = this._onMessageFromWorker;
  54262. var message = {
  54263. payload: {},
  54264. taskType: WorkerTaskType.INIT
  54265. };
  54266. this._worker.postMessage(message);
  54267. };
  54268. CollisionCoordinatorWorker.prototype.destroy = function () {
  54269. this._scene.unregisterAfterRender(this._afterRender);
  54270. this._worker.terminate();
  54271. };
  54272. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54273. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54274. this.onMeshUpdated(mesh);
  54275. };
  54276. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54277. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54278. };
  54279. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54280. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54281. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54282. this.onGeometryUpdated(geometry);
  54283. };
  54284. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54285. this._toRemoveGeometryArray.push(geometry.id);
  54286. };
  54287. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54288. var submeshes = [];
  54289. if (mesh.subMeshes) {
  54290. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54291. var boundingInfo = sm.getBoundingInfo();
  54292. return {
  54293. position: idx,
  54294. verticesStart: sm.verticesStart,
  54295. verticesCount: sm.verticesCount,
  54296. indexStart: sm.indexStart,
  54297. indexCount: sm.indexCount,
  54298. hasMaterial: !!sm.getMaterial(),
  54299. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54300. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54301. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54302. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54303. };
  54304. });
  54305. }
  54306. var geometryId = null;
  54307. if (mesh instanceof BABYLON.Mesh) {
  54308. var geometry = mesh.geometry;
  54309. geometryId = geometry ? geometry.id : null;
  54310. }
  54311. else if (mesh instanceof BABYLON.InstancedMesh) {
  54312. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54313. geometryId = geometry ? geometry.id : null;
  54314. }
  54315. var boundingInfo = mesh.getBoundingInfo();
  54316. return {
  54317. uniqueId: mesh.uniqueId,
  54318. id: mesh.id,
  54319. name: mesh.name,
  54320. geometryId: geometryId,
  54321. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54322. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54323. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54324. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54325. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54326. subMeshes: submeshes,
  54327. checkCollisions: mesh.checkCollisions
  54328. };
  54329. };
  54330. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54331. return {
  54332. id: geometry.id,
  54333. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54334. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54335. indices: new Uint32Array(geometry.getIndices() || []),
  54336. };
  54337. };
  54338. return CollisionCoordinatorWorker;
  54339. }());
  54340. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54341. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54342. function CollisionCoordinatorLegacy() {
  54343. this._scaledPosition = BABYLON.Vector3.Zero();
  54344. this._scaledVelocity = BABYLON.Vector3.Zero();
  54345. this._finalPosition = BABYLON.Vector3.Zero();
  54346. }
  54347. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54348. position.divideToRef(collider._radius, this._scaledPosition);
  54349. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54350. collider.collidedMesh = null;
  54351. collider._retry = 0;
  54352. collider._initialVelocity = this._scaledVelocity;
  54353. collider._initialPosition = this._scaledPosition;
  54354. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54355. this._finalPosition.multiplyInPlace(collider._radius);
  54356. //run the callback
  54357. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54358. };
  54359. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54360. this._scene = scene;
  54361. };
  54362. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54363. //Legacy need no destruction method.
  54364. };
  54365. //No update in legacy mode
  54366. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54367. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54368. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54369. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54370. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54371. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54372. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54373. if (excludedMesh === void 0) { excludedMesh = null; }
  54374. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54375. if (collider._retry >= maximumRetry) {
  54376. finalPosition.copyFrom(position);
  54377. return;
  54378. }
  54379. // Check if this is a mesh else camera or -1
  54380. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54381. collider._initialize(position, velocity, closeDistance);
  54382. // Check all meshes
  54383. for (var index = 0; index < this._scene.meshes.length; index++) {
  54384. var mesh = this._scene.meshes[index];
  54385. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54386. mesh._checkCollision(collider);
  54387. }
  54388. }
  54389. if (!collider.collisionFound) {
  54390. position.addToRef(velocity, finalPosition);
  54391. return;
  54392. }
  54393. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54394. collider._getResponse(position, velocity);
  54395. }
  54396. if (velocity.length() <= closeDistance) {
  54397. finalPosition.copyFrom(position);
  54398. return;
  54399. }
  54400. collider._retry++;
  54401. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54402. };
  54403. return CollisionCoordinatorLegacy;
  54404. }());
  54405. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54406. })(BABYLON || (BABYLON = {}));
  54407. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54408. var BABYLON;
  54409. (function (BABYLON) {
  54410. /**
  54411. * A particle represents one of the element emitted by a particle system.
  54412. * This is mainly define by its coordinates, direction, velocity and age.
  54413. */
  54414. var Particle = /** @class */ (function () {
  54415. /**
  54416. * Creates a new instance Particle
  54417. * @param particleSystem the particle system the particle belongs to
  54418. */
  54419. function Particle(
  54420. /**
  54421. * particleSystem the particle system the particle belongs to.
  54422. */
  54423. particleSystem) {
  54424. this.particleSystem = particleSystem;
  54425. /**
  54426. * The world position of the particle in the scene.
  54427. */
  54428. this.position = BABYLON.Vector3.Zero();
  54429. /**
  54430. * The world direction of the particle in the scene.
  54431. */
  54432. this.direction = BABYLON.Vector3.Zero();
  54433. /**
  54434. * The color of the particle.
  54435. */
  54436. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54437. /**
  54438. * The color change of the particle per step.
  54439. */
  54440. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54441. /**
  54442. * Defines how long will the life of the particle be.
  54443. */
  54444. this.lifeTime = 1.0;
  54445. /**
  54446. * The current age of the particle.
  54447. */
  54448. this.age = 0;
  54449. /**
  54450. * The current size of the particle.
  54451. */
  54452. this.size = 0;
  54453. /**
  54454. * The current scale of the particle.
  54455. */
  54456. this.scale = new BABYLON.Vector2(1, 1);
  54457. /**
  54458. * The current angle of the particle.
  54459. */
  54460. this.angle = 0;
  54461. /**
  54462. * Defines how fast is the angle changing.
  54463. */
  54464. this.angularSpeed = 0;
  54465. /**
  54466. * Defines the cell index used by the particle to be rendered from a sprite.
  54467. */
  54468. this.cellIndex = 0;
  54469. /** @hidden */
  54470. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54471. /** @hidden */
  54472. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54473. /** @hidden */
  54474. this._currentSize1 = 0;
  54475. /** @hidden */
  54476. this._currentSize2 = 0;
  54477. /** @hidden */
  54478. this._currentAngularSpeed1 = 0;
  54479. /** @hidden */
  54480. this._currentAngularSpeed2 = 0;
  54481. /** @hidden */
  54482. this._currentVelocity1 = 0;
  54483. /** @hidden */
  54484. this._currentVelocity2 = 0;
  54485. if (!this.particleSystem.isAnimationSheetEnabled) {
  54486. return;
  54487. }
  54488. this.updateCellInfoFromSystem();
  54489. }
  54490. Particle.prototype.updateCellInfoFromSystem = function () {
  54491. this.cellIndex = this.particleSystem.startSpriteCellID;
  54492. };
  54493. /**
  54494. * Defines how the sprite cell index is updated for the particle
  54495. */
  54496. Particle.prototype.updateCellIndex = function () {
  54497. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54498. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54499. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54500. };
  54501. /**
  54502. * Copy the properties of particle to another one.
  54503. * @param other the particle to copy the information to.
  54504. */
  54505. Particle.prototype.copyTo = function (other) {
  54506. other.position.copyFrom(this.position);
  54507. if (this._initialDirection) {
  54508. if (other._initialDirection) {
  54509. other._initialDirection.copyFrom(this._initialDirection);
  54510. }
  54511. else {
  54512. other._initialDirection = this._initialDirection.clone();
  54513. }
  54514. }
  54515. else {
  54516. other._initialDirection = null;
  54517. }
  54518. other.direction.copyFrom(this.direction);
  54519. other.color.copyFrom(this.color);
  54520. other.colorStep.copyFrom(this.colorStep);
  54521. other.lifeTime = this.lifeTime;
  54522. other.age = this.age;
  54523. other.size = this.size;
  54524. other.scale.copyFrom(this.scale);
  54525. other.angle = this.angle;
  54526. other.angularSpeed = this.angularSpeed;
  54527. other.particleSystem = this.particleSystem;
  54528. other.cellIndex = this.cellIndex;
  54529. if (this._currentColorGradient) {
  54530. other._currentColorGradient = this._currentColorGradient;
  54531. other._currentColor1.copyFrom(this._currentColor1);
  54532. other._currentColor2.copyFrom(this._currentColor2);
  54533. }
  54534. if (this._currentSizeGradient) {
  54535. other._currentSizeGradient = this._currentSizeGradient;
  54536. other._currentSize1 = this._currentSize1;
  54537. other._currentSize2 = this._currentSize2;
  54538. }
  54539. if (this._currentAngularSpeedGradient) {
  54540. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54541. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54542. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54543. }
  54544. if (this._currentVelocityGradient) {
  54545. other._currentVelocityGradient = this._currentVelocityGradient;
  54546. other._currentVelocity1 = this._currentVelocity1;
  54547. other._currentVelocity2 = this._currentVelocity2;
  54548. }
  54549. if (this.particleSystem.isAnimationSheetEnabled) {
  54550. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54551. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54552. }
  54553. };
  54554. return Particle;
  54555. }());
  54556. BABYLON.Particle = Particle;
  54557. })(BABYLON || (BABYLON = {}));
  54558. //# sourceMappingURL=babylon.particle.js.map
  54559. var BABYLON;
  54560. (function (BABYLON) {
  54561. /**
  54562. * This represents a particle system in Babylon.
  54563. * 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.
  54564. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54565. * @example https://doc.babylonjs.com/babylon101/particles
  54566. */
  54567. var ParticleSystem = /** @class */ (function () {
  54568. /**
  54569. * Instantiates a particle system.
  54570. * 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.
  54571. * @param name The name of the particle system
  54572. * @param capacity The max number of particles alive at the same time
  54573. * @param scene The scene the particle system belongs to
  54574. * @param customEffect a custom effect used to change the way particles are rendered by default
  54575. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54576. * @param epsilon Offset used to render the particles
  54577. */
  54578. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54579. if (customEffect === void 0) { customEffect = null; }
  54580. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54581. if (epsilon === void 0) { epsilon = 0.01; }
  54582. var _this = this;
  54583. /**
  54584. * List of animations used by the particle system.
  54585. */
  54586. this.animations = [];
  54587. /**
  54588. * The rendering group used by the Particle system to chose when to render.
  54589. */
  54590. this.renderingGroupId = 0;
  54591. /**
  54592. * The emitter represents the Mesh or position we are attaching the particle system to.
  54593. */
  54594. this.emitter = null;
  54595. /**
  54596. * The maximum number of particles to emit per frame
  54597. */
  54598. this.emitRate = 10;
  54599. /**
  54600. * If you want to launch only a few particles at once, that can be done, as well.
  54601. */
  54602. this.manualEmitCount = -1;
  54603. /**
  54604. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54605. */
  54606. this.updateSpeed = 0.01;
  54607. /**
  54608. * The amount of time the particle system is running (depends of the overall update speed).
  54609. */
  54610. this.targetStopDuration = 0;
  54611. /**
  54612. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54613. */
  54614. this.disposeOnStop = false;
  54615. /**
  54616. * Minimum power of emitting particles.
  54617. */
  54618. this.minEmitPower = 1;
  54619. /**
  54620. * Maximum power of emitting particles.
  54621. */
  54622. this.maxEmitPower = 1;
  54623. /**
  54624. * Minimum life time of emitting particles.
  54625. */
  54626. this.minLifeTime = 1;
  54627. /**
  54628. * Maximum life time of emitting particles.
  54629. */
  54630. this.maxLifeTime = 1;
  54631. /**
  54632. * Minimum Size of emitting particles.
  54633. */
  54634. this.minSize = 1;
  54635. /**
  54636. * Maximum Size of emitting particles.
  54637. */
  54638. this.maxSize = 1;
  54639. /**
  54640. * Minimum scale of emitting particles on X axis.
  54641. */
  54642. this.minScaleX = 1;
  54643. /**
  54644. * Maximum scale of emitting particles on X axis.
  54645. */
  54646. this.maxScaleX = 1;
  54647. /**
  54648. * Minimum scale of emitting particles on Y axis.
  54649. */
  54650. this.minScaleY = 1;
  54651. /**
  54652. * Maximum scale of emitting particles on Y axis.
  54653. */
  54654. this.maxScaleY = 1;
  54655. /**
  54656. * Gets or sets the minimal initial rotation in radians.
  54657. */
  54658. this.minInitialRotation = 0;
  54659. /**
  54660. * Gets or sets the maximal initial rotation in radians.
  54661. */
  54662. this.maxInitialRotation = 0;
  54663. /**
  54664. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54665. */
  54666. this.minAngularSpeed = 0;
  54667. /**
  54668. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54669. */
  54670. this.maxAngularSpeed = 0;
  54671. /**
  54672. * The layer mask we are rendering the particles through.
  54673. */
  54674. this.layerMask = 0x0FFFFFFF;
  54675. /**
  54676. * This can help using your own shader to render the particle system.
  54677. * The according effect will be created
  54678. */
  54679. this.customShader = null;
  54680. /**
  54681. * By default particle system starts as soon as they are created. This prevents the
  54682. * automatic start to happen and let you decide when to start emitting particles.
  54683. */
  54684. this.preventAutoStart = false;
  54685. /**
  54686. * Callback triggered when the particle animation is ending.
  54687. */
  54688. this.onAnimationEnd = null;
  54689. /**
  54690. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54691. */
  54692. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54693. /**
  54694. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54695. * to override the particles.
  54696. */
  54697. this.forceDepthWrite = false;
  54698. /**
  54699. * You can use gravity if you want to give an orientation to your particles.
  54700. */
  54701. this.gravity = BABYLON.Vector3.Zero();
  54702. this._colorGradients = null;
  54703. this._sizeGradients = null;
  54704. this._lifeTimeGradients = null;
  54705. this._angularSpeedGradients = null;
  54706. this._velocityGradients = null;
  54707. /**
  54708. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54709. */
  54710. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54711. /**
  54712. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  54713. */
  54714. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54715. /**
  54716. * Color the particle will have at the end of its lifetime
  54717. */
  54718. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54719. /**
  54720. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  54721. */
  54722. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54723. /**
  54724. * 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)
  54725. */
  54726. this.spriteCellChangeSpeed = 1;
  54727. /**
  54728. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  54729. */
  54730. this.startSpriteCellID = 0;
  54731. /**
  54732. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  54733. */
  54734. this.endSpriteCellID = 0;
  54735. /**
  54736. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  54737. */
  54738. this.spriteCellWidth = 0;
  54739. /**
  54740. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  54741. */
  54742. this.spriteCellHeight = 0;
  54743. /** 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 */
  54744. this.preWarmCycles = 0;
  54745. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  54746. this.preWarmStepOffset = 1;
  54747. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  54748. this.translationPivot = new BABYLON.Vector2(0, 0);
  54749. /**
  54750. * An event triggered when the system is disposed
  54751. */
  54752. this.onDisposeObservable = new BABYLON.Observable();
  54753. /**
  54754. * Gets or sets the billboard mode to use when isBillboardBased = true.
  54755. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  54756. */
  54757. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54758. this._particles = new Array();
  54759. this._stockParticles = new Array();
  54760. this._newPartsExcess = 0;
  54761. this._vertexBuffers = {};
  54762. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54763. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54764. this._scaledDirection = BABYLON.Vector3.Zero();
  54765. this._scaledGravity = BABYLON.Vector3.Zero();
  54766. this._currentRenderId = -1;
  54767. this._useInstancing = false;
  54768. this._started = false;
  54769. this._stopped = false;
  54770. this._actualFrame = 0;
  54771. this._isBillboardBased = true;
  54772. // start of sub system methods
  54773. /**
  54774. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54775. * Its lifetime will start back at 0.
  54776. */
  54777. this.recycleParticle = function (particle) {
  54778. var lastParticle = _this._particles.pop();
  54779. if (lastParticle !== particle) {
  54780. lastParticle.copyTo(particle);
  54781. }
  54782. _this._stockParticles.push(lastParticle);
  54783. };
  54784. this._createParticle = function () {
  54785. var particle;
  54786. if (_this._stockParticles.length !== 0) {
  54787. particle = _this._stockParticles.pop();
  54788. particle.age = 0;
  54789. particle._currentColorGradient = null;
  54790. particle.cellIndex = _this.startSpriteCellID;
  54791. }
  54792. else {
  54793. particle = new BABYLON.Particle(_this);
  54794. }
  54795. return particle;
  54796. };
  54797. this._emitFromParticle = function (particle) {
  54798. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54799. return;
  54800. }
  54801. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54802. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54803. subSystem._rootParticleSystem = _this;
  54804. _this.activeSubSystems.push(subSystem);
  54805. subSystem.start();
  54806. };
  54807. this.id = name;
  54808. this.name = name;
  54809. this._capacity = capacity;
  54810. this._epsilon = epsilon;
  54811. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54813. this._customEffect = customEffect;
  54814. scene.particleSystems.push(this);
  54815. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  54816. this._createIndexBuffer();
  54817. this._createVertexBuffers();
  54818. // Default emitter type
  54819. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54820. this.updateFunction = function (particles) {
  54821. var _loop_1 = function () {
  54822. particle = particles[index];
  54823. particle.age += _this._scaledUpdateSpeed;
  54824. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  54825. _this._emitFromParticle(particle);
  54826. _this.recycleParticle(particle);
  54827. index--;
  54828. return "continue";
  54829. }
  54830. else {
  54831. var ratio = particle.age / particle.lifeTime;
  54832. // Color
  54833. if (_this._colorGradients && _this._colorGradients.length > 0) {
  54834. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  54835. if (currentGradient !== particle._currentColorGradient) {
  54836. particle._currentColor1.copyFrom(particle._currentColor2);
  54837. nextGradient.getColorToRef(particle._currentColor2);
  54838. particle._currentColorGradient = currentGradient;
  54839. }
  54840. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  54841. });
  54842. }
  54843. else {
  54844. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54845. particle.color.addInPlace(_this._scaledColorStep);
  54846. if (particle.color.a < 0) {
  54847. particle.color.a = 0;
  54848. }
  54849. }
  54850. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  54851. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  54852. if (currentGradient !== particle._currentAngularSpeedGradient) {
  54853. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  54854. particle._currentAngularSpeed2 = nextGradient.getFactor();
  54855. particle._currentAngularSpeedGradient = currentGradient;
  54856. }
  54857. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  54858. });
  54859. }
  54860. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54861. var directionScale_1 = _this._scaledUpdateSpeed;
  54862. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  54863. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  54864. if (currentGradient !== particle._currentVelocityGradient) {
  54865. particle._currentVelocity1 = particle._currentVelocity2;
  54866. particle._currentVelocity2 = nextGradient.getFactor();
  54867. particle._currentVelocityGradient = currentGradient;
  54868. }
  54869. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  54870. });
  54871. }
  54872. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  54873. particle.position.addInPlace(_this._scaledDirection);
  54874. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54875. particle.direction.addInPlace(_this._scaledGravity);
  54876. // Size
  54877. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  54878. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  54879. if (currentGradient !== particle._currentSizeGradient) {
  54880. particle._currentSize1 = particle._currentSize2;
  54881. particle._currentSize2 = nextGradient.getFactor();
  54882. particle._currentSizeGradient = currentGradient;
  54883. }
  54884. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  54885. });
  54886. }
  54887. if (_this._isAnimationSheetEnabled) {
  54888. particle.updateCellIndex();
  54889. }
  54890. }
  54891. };
  54892. var particle;
  54893. for (var index = 0; index < particles.length; index++) {
  54894. _loop_1();
  54895. }
  54896. };
  54897. }
  54898. /**
  54899. * Gets the current list of color gradients.
  54900. * You must use addColorGradient and removeColorGradient to udpate this list
  54901. * @returns the list of color gradients
  54902. */
  54903. ParticleSystem.prototype.getColorGradients = function () {
  54904. return this._colorGradients;
  54905. };
  54906. /**
  54907. * Gets the current list of size gradients.
  54908. * You must use addSizeGradient and removeSizeGradient to udpate this list
  54909. * @returns the list of size gradients
  54910. */
  54911. ParticleSystem.prototype.getSizeGradients = function () {
  54912. return this._sizeGradients;
  54913. };
  54914. /**
  54915. * Gets the current list of life time gradients.
  54916. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  54917. * @returns the list of life time gradients
  54918. */
  54919. ParticleSystem.prototype.getLifeTimeGradients = function () {
  54920. return this._lifeTimeGradients;
  54921. };
  54922. /**
  54923. * Gets the current list of angular speed gradients.
  54924. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  54925. * @returns the list of angular speed gradients
  54926. */
  54927. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  54928. return this._angularSpeedGradients;
  54929. };
  54930. /**
  54931. * Gets the current list of velocity gradients.
  54932. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  54933. * @returns the list of velocity gradients
  54934. */
  54935. ParticleSystem.prototype.getVelocityGradients = function () {
  54936. return this._velocityGradients;
  54937. };
  54938. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54939. /**
  54940. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54941. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54942. */
  54943. get: function () {
  54944. if (this.particleEmitterType.direction1) {
  54945. return this.particleEmitterType.direction1;
  54946. }
  54947. return BABYLON.Vector3.Zero();
  54948. },
  54949. set: function (value) {
  54950. if (this.particleEmitterType.direction1) {
  54951. this.particleEmitterType.direction1 = value;
  54952. }
  54953. },
  54954. enumerable: true,
  54955. configurable: true
  54956. });
  54957. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54958. /**
  54959. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54960. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54961. */
  54962. get: function () {
  54963. if (this.particleEmitterType.direction2) {
  54964. return this.particleEmitterType.direction2;
  54965. }
  54966. return BABYLON.Vector3.Zero();
  54967. },
  54968. set: function (value) {
  54969. if (this.particleEmitterType.direction2) {
  54970. this.particleEmitterType.direction2 = value;
  54971. }
  54972. },
  54973. enumerable: true,
  54974. configurable: true
  54975. });
  54976. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54977. /**
  54978. * 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.
  54979. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54980. */
  54981. get: function () {
  54982. if (this.particleEmitterType.minEmitBox) {
  54983. return this.particleEmitterType.minEmitBox;
  54984. }
  54985. return BABYLON.Vector3.Zero();
  54986. },
  54987. set: function (value) {
  54988. if (this.particleEmitterType.minEmitBox) {
  54989. this.particleEmitterType.minEmitBox = value;
  54990. }
  54991. },
  54992. enumerable: true,
  54993. configurable: true
  54994. });
  54995. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54996. /**
  54997. * 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.
  54998. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54999. */
  55000. get: function () {
  55001. if (this.particleEmitterType.maxEmitBox) {
  55002. return this.particleEmitterType.maxEmitBox;
  55003. }
  55004. return BABYLON.Vector3.Zero();
  55005. },
  55006. set: function (value) {
  55007. if (this.particleEmitterType.maxEmitBox) {
  55008. this.particleEmitterType.maxEmitBox = value;
  55009. }
  55010. },
  55011. enumerable: true,
  55012. configurable: true
  55013. });
  55014. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55015. /**
  55016. * Sets a callback that will be triggered when the system is disposed
  55017. */
  55018. set: function (callback) {
  55019. if (this._onDisposeObserver) {
  55020. this.onDisposeObservable.remove(this._onDisposeObserver);
  55021. }
  55022. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55023. },
  55024. enumerable: true,
  55025. configurable: true
  55026. });
  55027. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55028. /**
  55029. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55030. */
  55031. get: function () {
  55032. return this._isAnimationSheetEnabled;
  55033. },
  55034. enumerable: true,
  55035. configurable: true
  55036. });
  55037. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55038. /**
  55039. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55040. */
  55041. get: function () {
  55042. return this._isBillboardBased;
  55043. },
  55044. set: function (value) {
  55045. if (this._isBillboardBased === value) {
  55046. return;
  55047. }
  55048. this._isBillboardBased = value;
  55049. this._resetEffect();
  55050. },
  55051. enumerable: true,
  55052. configurable: true
  55053. });
  55054. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55055. //end of Sub-emitter
  55056. /**
  55057. * Gets the current list of active particles
  55058. */
  55059. get: function () {
  55060. return this._particles;
  55061. },
  55062. enumerable: true,
  55063. configurable: true
  55064. });
  55065. /**
  55066. * Returns the string "ParticleSystem"
  55067. * @returns a string containing the class name
  55068. */
  55069. ParticleSystem.prototype.getClassName = function () {
  55070. return "ParticleSystem";
  55071. };
  55072. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55073. var newGradient = new BABYLON.FactorGradient();
  55074. newGradient.gradient = gradient;
  55075. newGradient.factor1 = factor;
  55076. newGradient.factor2 = factor2;
  55077. factorGradients.push(newGradient);
  55078. factorGradients.sort(function (a, b) {
  55079. if (a.gradient < b.gradient) {
  55080. return -1;
  55081. }
  55082. else if (a.gradient > b.gradient) {
  55083. return 1;
  55084. }
  55085. return 0;
  55086. });
  55087. };
  55088. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55089. if (!factorGradients) {
  55090. return;
  55091. }
  55092. var index = 0;
  55093. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55094. var factorGradient = factorGradients_1[_i];
  55095. if (factorGradient.gradient === gradient) {
  55096. factorGradients.splice(index, 1);
  55097. break;
  55098. }
  55099. index++;
  55100. }
  55101. };
  55102. /**
  55103. * Adds a new life time gradient
  55104. * @param gradient defines the gradient to use (between 0 and 1)
  55105. * @param factor defines the life time factor to affect to the specified gradient
  55106. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55107. * @returns the current particle system
  55108. */
  55109. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55110. if (!this._lifeTimeGradients) {
  55111. this._lifeTimeGradients = [];
  55112. }
  55113. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55114. return this;
  55115. };
  55116. /**
  55117. * Remove a specific life time gradient
  55118. * @param gradient defines the gradient to remove
  55119. * @returns the current particle system
  55120. */
  55121. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55122. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55123. return this;
  55124. };
  55125. /**
  55126. * Adds a new size gradient
  55127. * @param gradient defines the gradient to use (between 0 and 1)
  55128. * @param factor defines the size factor to affect to the specified gradient
  55129. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55130. * @returns the current particle system
  55131. */
  55132. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55133. if (!this._sizeGradients) {
  55134. this._sizeGradients = [];
  55135. }
  55136. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55137. return this;
  55138. };
  55139. /**
  55140. * Remove a specific size gradient
  55141. * @param gradient defines the gradient to remove
  55142. * @returns the current particle system
  55143. */
  55144. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55145. this._removeFactorGradient(this._sizeGradients, gradient);
  55146. return this;
  55147. };
  55148. /**
  55149. * Adds a new angular speed gradient
  55150. * @param gradient defines the gradient to use (between 0 and 1)
  55151. * @param factor defines the size factor to affect to the specified gradient
  55152. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55153. * @returns the current particle system
  55154. */
  55155. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55156. if (!this._angularSpeedGradients) {
  55157. this._angularSpeedGradients = [];
  55158. }
  55159. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55160. return this;
  55161. };
  55162. /**
  55163. * Remove a specific angular speed gradient
  55164. * @param gradient defines the gradient to remove
  55165. * @returns the current particle system
  55166. */
  55167. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55168. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55169. return this;
  55170. };
  55171. /**
  55172. * Adds a new velocity gradient
  55173. * @param gradient defines the gradient to use (between 0 and 1)
  55174. * @param factor defines the size factor to affect to the specified gradient
  55175. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55176. * @returns the current particle system
  55177. */
  55178. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55179. if (!this._velocityGradients) {
  55180. this._velocityGradients = [];
  55181. }
  55182. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55183. return this;
  55184. };
  55185. /**
  55186. * Remove a specific velocity gradient
  55187. * @param gradient defines the gradient to remove
  55188. * @returns the current particle system
  55189. */
  55190. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55191. this._removeFactorGradient(this._velocityGradients, gradient);
  55192. return this;
  55193. };
  55194. /**
  55195. * Adds a new color gradient
  55196. * @param gradient defines the gradient to use (between 0 and 1)
  55197. * @param color defines the color to affect to the specified gradient
  55198. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55199. */
  55200. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55201. if (!this._colorGradients) {
  55202. this._colorGradients = [];
  55203. }
  55204. var colorGradient = new BABYLON.ColorGradient();
  55205. colorGradient.gradient = gradient;
  55206. colorGradient.color1 = color;
  55207. colorGradient.color2 = color2;
  55208. this._colorGradients.push(colorGradient);
  55209. this._colorGradients.sort(function (a, b) {
  55210. if (a.gradient < b.gradient) {
  55211. return -1;
  55212. }
  55213. else if (a.gradient > b.gradient) {
  55214. return 1;
  55215. }
  55216. return 0;
  55217. });
  55218. return this;
  55219. };
  55220. /**
  55221. * Remove a specific color gradient
  55222. * @param gradient defines the gradient to remove
  55223. */
  55224. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55225. if (!this._colorGradients) {
  55226. return this;
  55227. }
  55228. var index = 0;
  55229. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55230. var colorGradient = _a[_i];
  55231. if (colorGradient.gradient === gradient) {
  55232. this._colorGradients.splice(index, 1);
  55233. break;
  55234. }
  55235. index++;
  55236. }
  55237. return this;
  55238. };
  55239. ParticleSystem.prototype._resetEffect = function () {
  55240. if (this._vertexBuffer) {
  55241. this._vertexBuffer.dispose();
  55242. this._vertexBuffer = null;
  55243. }
  55244. if (this._spriteBuffer) {
  55245. this._spriteBuffer.dispose();
  55246. this._spriteBuffer = null;
  55247. }
  55248. this._createVertexBuffers();
  55249. };
  55250. ParticleSystem.prototype._createVertexBuffers = function () {
  55251. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55252. if (this._isAnimationSheetEnabled) {
  55253. this._vertexBufferSize += 1;
  55254. }
  55255. if (!this._isBillboardBased) {
  55256. this._vertexBufferSize += 3;
  55257. }
  55258. var engine = this._scene.getEngine();
  55259. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55260. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55261. var dataOffset = 0;
  55262. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55264. dataOffset += 3;
  55265. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55266. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55267. dataOffset += 4;
  55268. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55269. this._vertexBuffers["angle"] = options;
  55270. dataOffset += 1;
  55271. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55272. this._vertexBuffers["size"] = size;
  55273. dataOffset += 2;
  55274. if (this._isAnimationSheetEnabled) {
  55275. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55276. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55277. dataOffset += 1;
  55278. }
  55279. if (!this._isBillboardBased) {
  55280. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55281. this._vertexBuffers["direction"] = directionBuffer;
  55282. dataOffset += 3;
  55283. }
  55284. var offsets;
  55285. if (this._useInstancing) {
  55286. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55287. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55288. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55289. }
  55290. else {
  55291. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55292. dataOffset += 2;
  55293. }
  55294. this._vertexBuffers["offset"] = offsets;
  55295. };
  55296. ParticleSystem.prototype._createIndexBuffer = function () {
  55297. if (this._useInstancing) {
  55298. return;
  55299. }
  55300. var indices = [];
  55301. var index = 0;
  55302. for (var count = 0; count < this._capacity; count++) {
  55303. indices.push(index);
  55304. indices.push(index + 1);
  55305. indices.push(index + 2);
  55306. indices.push(index);
  55307. indices.push(index + 2);
  55308. indices.push(index + 3);
  55309. index += 4;
  55310. }
  55311. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55312. };
  55313. /**
  55314. * Gets the maximum number of particles active at the same time.
  55315. * @returns The max number of active particles.
  55316. */
  55317. ParticleSystem.prototype.getCapacity = function () {
  55318. return this._capacity;
  55319. };
  55320. /**
  55321. * Gets Wether there are still active particles in the system.
  55322. * @returns True if it is alive, otherwise false.
  55323. */
  55324. ParticleSystem.prototype.isAlive = function () {
  55325. return this._alive;
  55326. };
  55327. /**
  55328. * Gets Wether the system has been started.
  55329. * @returns True if it has been started, otherwise false.
  55330. */
  55331. ParticleSystem.prototype.isStarted = function () {
  55332. return this._started;
  55333. };
  55334. /**
  55335. * Starts the particle system and begins to emit.
  55336. */
  55337. ParticleSystem.prototype.start = function () {
  55338. this._started = true;
  55339. this._stopped = false;
  55340. this._actualFrame = 0;
  55341. if (this.subEmitters && this.subEmitters.length != 0) {
  55342. this.activeSubSystems = new Array();
  55343. }
  55344. if (this.preWarmCycles) {
  55345. for (var index = 0; index < this.preWarmCycles; index++) {
  55346. this.animate(true);
  55347. }
  55348. }
  55349. };
  55350. /**
  55351. * Stops the particle system.
  55352. * @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.
  55353. */
  55354. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55355. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55356. this._stopped = true;
  55357. if (stopSubEmitters) {
  55358. this._stopSubEmitters();
  55359. }
  55360. };
  55361. // animation sheet
  55362. /**
  55363. * Remove all active particles
  55364. */
  55365. ParticleSystem.prototype.reset = function () {
  55366. this._stockParticles = [];
  55367. this._particles = [];
  55368. };
  55369. /**
  55370. * @hidden (for internal use only)
  55371. */
  55372. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55373. var offset = index * this._vertexBufferSize;
  55374. this._vertexData[offset++] = particle.position.x;
  55375. this._vertexData[offset++] = particle.position.y;
  55376. this._vertexData[offset++] = particle.position.z;
  55377. this._vertexData[offset++] = particle.color.r;
  55378. this._vertexData[offset++] = particle.color.g;
  55379. this._vertexData[offset++] = particle.color.b;
  55380. this._vertexData[offset++] = particle.color.a;
  55381. this._vertexData[offset++] = particle.angle;
  55382. this._vertexData[offset++] = particle.scale.x * particle.size;
  55383. this._vertexData[offset++] = particle.scale.y * particle.size;
  55384. if (this._isAnimationSheetEnabled) {
  55385. this._vertexData[offset++] = particle.cellIndex;
  55386. }
  55387. if (!this._isBillboardBased) {
  55388. if (particle._initialDirection) {
  55389. this._vertexData[offset++] = particle._initialDirection.x;
  55390. this._vertexData[offset++] = particle._initialDirection.y;
  55391. this._vertexData[offset++] = particle._initialDirection.z;
  55392. }
  55393. else {
  55394. this._vertexData[offset++] = particle.direction.x;
  55395. this._vertexData[offset++] = particle.direction.y;
  55396. this._vertexData[offset++] = particle.direction.z;
  55397. }
  55398. }
  55399. if (!this._useInstancing) {
  55400. if (this._isAnimationSheetEnabled) {
  55401. if (offsetX === 0)
  55402. offsetX = this._epsilon;
  55403. else if (offsetX === 1)
  55404. offsetX = 1 - this._epsilon;
  55405. if (offsetY === 0)
  55406. offsetY = this._epsilon;
  55407. else if (offsetY === 1)
  55408. offsetY = 1 - this._epsilon;
  55409. }
  55410. this._vertexData[offset++] = offsetX;
  55411. this._vertexData[offset++] = offsetY;
  55412. }
  55413. };
  55414. ParticleSystem.prototype._stopSubEmitters = function () {
  55415. if (!this.activeSubSystems) {
  55416. return;
  55417. }
  55418. this.activeSubSystems.forEach(function (subSystem) {
  55419. subSystem.stop(true);
  55420. });
  55421. this.activeSubSystems = new Array();
  55422. };
  55423. ParticleSystem.prototype._removeFromRoot = function () {
  55424. if (!this._rootParticleSystem) {
  55425. return;
  55426. }
  55427. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55428. if (index !== -1) {
  55429. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55430. }
  55431. };
  55432. // End of sub system methods
  55433. ParticleSystem.prototype._update = function (newParticles) {
  55434. // Update current
  55435. this._alive = this._particles.length > 0;
  55436. this.updateFunction(this._particles);
  55437. // Add new ones
  55438. var worldMatrix;
  55439. if (this.emitter.position) {
  55440. var emitterMesh = this.emitter;
  55441. worldMatrix = emitterMesh.getWorldMatrix();
  55442. }
  55443. else {
  55444. var emitterPosition = this.emitter;
  55445. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55446. }
  55447. var particle;
  55448. var _loop_2 = function () {
  55449. if (this_1._particles.length === this_1._capacity) {
  55450. return "break";
  55451. }
  55452. particle = this_1._createParticle();
  55453. this_1._particles.push(particle);
  55454. // Emitter
  55455. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55456. if (this_1.startPositionFunction) {
  55457. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55458. }
  55459. else {
  55460. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55461. }
  55462. if (this_1.startDirectionFunction) {
  55463. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55464. }
  55465. else {
  55466. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55467. }
  55468. if (emitPower === 0) {
  55469. if (!particle._initialDirection) {
  55470. particle._initialDirection = particle.direction.clone();
  55471. }
  55472. else {
  55473. particle._initialDirection.copyFrom(particle.direction);
  55474. }
  55475. }
  55476. else {
  55477. particle._initialDirection = null;
  55478. }
  55479. particle.direction.scaleInPlace(emitPower);
  55480. // Life time
  55481. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55482. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55483. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55484. var factorGradient1 = currentGradient;
  55485. var factorGradient2 = nextGradient;
  55486. var lifeTime1 = factorGradient1.getFactor();
  55487. var lifeTime2 = factorGradient2.getFactor();
  55488. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55489. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55490. });
  55491. }
  55492. else {
  55493. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55494. }
  55495. // Size
  55496. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55497. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55498. }
  55499. else {
  55500. particle._currentSizeGradient = this_1._sizeGradients[0];
  55501. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55502. particle.size = particle._currentSize1;
  55503. if (this_1._sizeGradients.length > 1) {
  55504. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55505. }
  55506. else {
  55507. particle._currentSize2 = particle._currentSize1;
  55508. }
  55509. }
  55510. // Size and scale
  55511. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55512. // Angle
  55513. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55514. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55515. }
  55516. else {
  55517. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55518. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55519. particle._currentAngularSpeed1 = particle.angularSpeed;
  55520. if (this_1._angularSpeedGradients.length > 1) {
  55521. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55522. }
  55523. else {
  55524. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55525. }
  55526. }
  55527. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55528. // Velocity
  55529. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55530. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55531. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55532. if (this_1._velocityGradients.length > 1) {
  55533. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55534. }
  55535. else {
  55536. particle._currentVelocity2 = particle._currentVelocity1;
  55537. }
  55538. }
  55539. // Color
  55540. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55541. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55542. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55543. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55544. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55545. }
  55546. else {
  55547. particle._currentColorGradient = this_1._colorGradients[0];
  55548. particle._currentColorGradient.getColorToRef(particle.color);
  55549. particle._currentColor1.copyFrom(particle.color);
  55550. if (this_1._colorGradients.length > 1) {
  55551. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55552. }
  55553. else {
  55554. particle._currentColor2.copyFrom(particle.color);
  55555. }
  55556. }
  55557. // Sheet
  55558. if (this_1._isAnimationSheetEnabled) {
  55559. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55560. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55561. }
  55562. };
  55563. var this_1 = this, step;
  55564. for (var index = 0; index < newParticles; index++) {
  55565. var state_1 = _loop_2();
  55566. if (state_1 === "break")
  55567. break;
  55568. }
  55569. };
  55570. /** @hidden */
  55571. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55572. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55573. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55574. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55575. if (isAnimationSheetEnabled) {
  55576. attributeNamesOrOptions.push("cellIndex");
  55577. }
  55578. if (!isBillboardBased) {
  55579. attributeNamesOrOptions.push("direction");
  55580. }
  55581. return attributeNamesOrOptions;
  55582. };
  55583. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55584. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55585. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55586. if (isAnimationSheetEnabled) {
  55587. effectCreationOption.push("particlesInfos");
  55588. }
  55589. return effectCreationOption;
  55590. };
  55591. ParticleSystem.prototype._getEffect = function () {
  55592. if (this._customEffect) {
  55593. return this._customEffect;
  55594. }
  55595. ;
  55596. var defines = [];
  55597. if (this._scene.clipPlane) {
  55598. defines.push("#define CLIPPLANE");
  55599. }
  55600. if (this._isAnimationSheetEnabled) {
  55601. defines.push("#define ANIMATESHEET");
  55602. }
  55603. if (this._isBillboardBased) {
  55604. defines.push("#define BILLBOARD");
  55605. switch (this.billboardMode) {
  55606. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55607. defines.push("#define BILLBOARDY");
  55608. break;
  55609. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55610. default:
  55611. break;
  55612. }
  55613. }
  55614. // Effect
  55615. var join = defines.join("\n");
  55616. if (this._cachedDefines !== join) {
  55617. this._cachedDefines = join;
  55618. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55619. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55620. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55621. }
  55622. return this._effect;
  55623. };
  55624. /**
  55625. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55626. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55627. */
  55628. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55629. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55630. if (!this._started)
  55631. return;
  55632. if (!preWarmOnly) {
  55633. var effect = this._getEffect();
  55634. // Check
  55635. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55636. return;
  55637. if (this._currentRenderId === this._scene.getRenderId()) {
  55638. return;
  55639. }
  55640. this._currentRenderId = this._scene.getRenderId();
  55641. }
  55642. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55643. // determine the number of particles we need to create
  55644. var newParticles;
  55645. if (this.manualEmitCount > -1) {
  55646. newParticles = this.manualEmitCount;
  55647. this._newPartsExcess = 0;
  55648. this.manualEmitCount = 0;
  55649. }
  55650. else {
  55651. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55652. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55653. }
  55654. if (this._newPartsExcess > 1.0) {
  55655. newParticles += this._newPartsExcess >> 0;
  55656. this._newPartsExcess -= this._newPartsExcess >> 0;
  55657. }
  55658. this._alive = false;
  55659. if (!this._stopped) {
  55660. this._actualFrame += this._scaledUpdateSpeed;
  55661. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55662. this.stop();
  55663. }
  55664. else {
  55665. newParticles = 0;
  55666. }
  55667. this._update(newParticles);
  55668. // Stopped?
  55669. if (this._stopped) {
  55670. if (!this._alive) {
  55671. this._started = false;
  55672. if (this.onAnimationEnd) {
  55673. this.onAnimationEnd();
  55674. }
  55675. if (this.disposeOnStop) {
  55676. this._scene._toBeDisposed.push(this);
  55677. }
  55678. }
  55679. }
  55680. if (!preWarmOnly) {
  55681. // Update VBO
  55682. var offset = 0;
  55683. for (var index = 0; index < this._particles.length; index++) {
  55684. var particle = this._particles[index];
  55685. this._appendParticleVertices(offset, particle);
  55686. offset += this._useInstancing ? 1 : 4;
  55687. }
  55688. if (this._vertexBuffer) {
  55689. this._vertexBuffer.update(this._vertexData);
  55690. }
  55691. }
  55692. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55693. this.stop();
  55694. }
  55695. };
  55696. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55697. this._appendParticleVertex(offset++, particle, 0, 0);
  55698. if (!this._useInstancing) {
  55699. this._appendParticleVertex(offset++, particle, 1, 0);
  55700. this._appendParticleVertex(offset++, particle, 1, 1);
  55701. this._appendParticleVertex(offset++, particle, 0, 1);
  55702. }
  55703. };
  55704. /**
  55705. * Rebuilds the particle system.
  55706. */
  55707. ParticleSystem.prototype.rebuild = function () {
  55708. this._createIndexBuffer();
  55709. if (this._vertexBuffer) {
  55710. this._vertexBuffer._rebuild();
  55711. }
  55712. };
  55713. /**
  55714. * Is this system ready to be used/rendered
  55715. * @return true if the system is ready
  55716. */
  55717. ParticleSystem.prototype.isReady = function () {
  55718. var effect = this._getEffect();
  55719. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55720. return false;
  55721. }
  55722. return true;
  55723. };
  55724. /**
  55725. * Renders the particle system in its current state.
  55726. * @returns the current number of particles
  55727. */
  55728. ParticleSystem.prototype.render = function () {
  55729. var effect = this._getEffect();
  55730. // Check
  55731. if (!this.isReady() || !this._particles.length) {
  55732. return 0;
  55733. }
  55734. var engine = this._scene.getEngine();
  55735. // Render
  55736. engine.enableEffect(effect);
  55737. engine.setState(false);
  55738. var viewMatrix = this._scene.getViewMatrix();
  55739. effect.setTexture("diffuseSampler", this.particleTexture);
  55740. effect.setMatrix("view", viewMatrix);
  55741. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55742. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55743. var baseSize = this.particleTexture.getBaseSize();
  55744. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55745. }
  55746. effect.setVector2("translationPivot", this.translationPivot);
  55747. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55748. if (this._isBillboardBased) {
  55749. var camera = this._scene.activeCamera;
  55750. effect.setVector3("eyePosition", camera.globalPosition);
  55751. }
  55752. if (this._scene.clipPlane) {
  55753. var clipPlane = this._scene.clipPlane;
  55754. var invView = viewMatrix.clone();
  55755. invView.invert();
  55756. effect.setMatrix("invView", invView);
  55757. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55758. }
  55759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55760. // Draw order
  55761. switch (this.blendMode) {
  55762. case ParticleSystem.BLENDMODE_ADD:
  55763. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55764. break;
  55765. case ParticleSystem.BLENDMODE_ONEONE:
  55766. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55767. break;
  55768. case ParticleSystem.BLENDMODE_STANDARD:
  55769. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55770. break;
  55771. }
  55772. if (this.forceDepthWrite) {
  55773. engine.setDepthWrite(true);
  55774. }
  55775. if (this._useInstancing) {
  55776. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55777. engine.unbindInstanceAttributes();
  55778. }
  55779. else {
  55780. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55781. }
  55782. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55783. return this._particles.length;
  55784. };
  55785. /**
  55786. * Disposes the particle system and free the associated resources
  55787. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55788. */
  55789. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55790. if (disposeTexture === void 0) { disposeTexture = true; }
  55791. if (this._vertexBuffer) {
  55792. this._vertexBuffer.dispose();
  55793. this._vertexBuffer = null;
  55794. }
  55795. if (this._spriteBuffer) {
  55796. this._spriteBuffer.dispose();
  55797. this._spriteBuffer = null;
  55798. }
  55799. if (this._indexBuffer) {
  55800. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55801. this._indexBuffer = null;
  55802. }
  55803. if (disposeTexture && this.particleTexture) {
  55804. this.particleTexture.dispose();
  55805. this.particleTexture = null;
  55806. }
  55807. this._removeFromRoot();
  55808. // Remove from scene
  55809. var index = this._scene.particleSystems.indexOf(this);
  55810. if (index > -1) {
  55811. this._scene.particleSystems.splice(index, 1);
  55812. }
  55813. // Callback
  55814. this.onDisposeObservable.notifyObservers(this);
  55815. this.onDisposeObservable.clear();
  55816. };
  55817. /**
  55818. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55819. * @param radius The radius of the sphere to emit from
  55820. * @returns the emitter
  55821. */
  55822. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55823. if (radius === void 0) { radius = 1; }
  55824. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55825. this.particleEmitterType = particleEmitter;
  55826. return particleEmitter;
  55827. };
  55828. /**
  55829. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55830. * @param radius The radius of the sphere to emit from
  55831. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55832. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55833. * @returns the emitter
  55834. */
  55835. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55836. if (radius === void 0) { radius = 1; }
  55837. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55838. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55839. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55840. this.particleEmitterType = particleEmitter;
  55841. return particleEmitter;
  55842. };
  55843. /**
  55844. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55845. * @param radius The radius of the cone to emit from
  55846. * @param angle The base angle of the cone
  55847. * @returns the emitter
  55848. */
  55849. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55850. if (radius === void 0) { radius = 1; }
  55851. if (angle === void 0) { angle = Math.PI / 4; }
  55852. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55853. this.particleEmitterType = particleEmitter;
  55854. return particleEmitter;
  55855. };
  55856. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  55857. /**
  55858. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55859. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55860. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55861. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55862. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55863. * @returns the emitter
  55864. */
  55865. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55866. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55867. this.particleEmitterType = particleEmitter;
  55868. this.direction1 = direction1;
  55869. this.direction2 = direction2;
  55870. this.minEmitBox = minEmitBox;
  55871. this.maxEmitBox = maxEmitBox;
  55872. return particleEmitter;
  55873. };
  55874. // Clone
  55875. /**
  55876. * Clones the particle system.
  55877. * @param name The name of the cloned object
  55878. * @param newEmitter The new emitter to use
  55879. * @returns the cloned particle system
  55880. */
  55881. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55882. var custom = null;
  55883. var program = null;
  55884. if (this.customShader != null) {
  55885. program = this.customShader;
  55886. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55887. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55888. }
  55889. else if (this._customEffect) {
  55890. custom = this._customEffect;
  55891. }
  55892. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55893. result.customShader = program;
  55894. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55895. if (newEmitter === undefined) {
  55896. newEmitter = this.emitter;
  55897. }
  55898. result.emitter = newEmitter;
  55899. if (this.particleTexture) {
  55900. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55901. }
  55902. if (!this.preventAutoStart) {
  55903. result.start();
  55904. }
  55905. return result;
  55906. };
  55907. /**
  55908. * Serializes the particle system to a JSON object.
  55909. * @returns the JSON object
  55910. */
  55911. ParticleSystem.prototype.serialize = function () {
  55912. var serializationObject = {};
  55913. ParticleSystem._Serialize(serializationObject, this);
  55914. serializationObject.textureMask = this.textureMask.asArray();
  55915. serializationObject.customShader = this.customShader;
  55916. serializationObject.preventAutoStart = this.preventAutoStart;
  55917. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55918. return serializationObject;
  55919. };
  55920. /** @hidden */
  55921. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55922. serializationObject.name = particleSystem.name;
  55923. serializationObject.id = particleSystem.id;
  55924. serializationObject.capacity = particleSystem.getCapacity();
  55925. // Emitter
  55926. if (particleSystem.emitter.position) {
  55927. var emitterMesh = particleSystem.emitter;
  55928. serializationObject.emitterId = emitterMesh.id;
  55929. }
  55930. else {
  55931. var emitterPosition = particleSystem.emitter;
  55932. serializationObject.emitter = emitterPosition.asArray();
  55933. }
  55934. // Emitter
  55935. if (particleSystem.particleEmitterType) {
  55936. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  55937. }
  55938. if (particleSystem.particleTexture) {
  55939. serializationObject.textureName = particleSystem.particleTexture.name;
  55940. }
  55941. // Animations
  55942. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  55943. // Particle system
  55944. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  55945. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  55946. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  55947. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  55948. serializationObject.minSize = particleSystem.minSize;
  55949. serializationObject.maxSize = particleSystem.maxSize;
  55950. serializationObject.minScaleX = particleSystem.minScaleX;
  55951. serializationObject.maxScaleX = particleSystem.maxScaleX;
  55952. serializationObject.minScaleY = particleSystem.minScaleY;
  55953. serializationObject.maxScaleY = particleSystem.maxScaleY;
  55954. serializationObject.minEmitPower = particleSystem.minEmitPower;
  55955. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  55956. serializationObject.minLifeTime = particleSystem.minLifeTime;
  55957. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  55958. serializationObject.emitRate = particleSystem.emitRate;
  55959. serializationObject.gravity = particleSystem.gravity.asArray();
  55960. serializationObject.color1 = particleSystem.color1.asArray();
  55961. serializationObject.color2 = particleSystem.color2.asArray();
  55962. serializationObject.colorDead = particleSystem.colorDead.asArray();
  55963. serializationObject.updateSpeed = particleSystem.updateSpeed;
  55964. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  55965. serializationObject.blendMode = particleSystem.blendMode;
  55966. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  55967. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  55968. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  55969. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  55970. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  55971. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  55972. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  55973. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  55974. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  55975. var colorGradients = particleSystem.getColorGradients();
  55976. if (colorGradients) {
  55977. serializationObject.colorGradients = [];
  55978. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  55979. var colorGradient = colorGradients_1[_i];
  55980. var serializedGradient = {
  55981. gradient: colorGradient.gradient,
  55982. color1: colorGradient.color1.asArray()
  55983. };
  55984. if (colorGradient.color2) {
  55985. serializedGradient.color2 = colorGradient.color2.asArray();
  55986. }
  55987. serializationObject.colorGradients.push(serializedGradient);
  55988. }
  55989. }
  55990. var sizeGradients = particleSystem.getSizeGradients();
  55991. if (sizeGradients) {
  55992. serializationObject.sizeGradients = [];
  55993. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  55994. var sizeGradient = sizeGradients_1[_a];
  55995. var serializedGradient = {
  55996. gradient: sizeGradient.gradient,
  55997. factor1: sizeGradient.factor1
  55998. };
  55999. if (sizeGradient.factor2 !== undefined) {
  56000. serializedGradient.factor2 = sizeGradient.factor2;
  56001. }
  56002. serializationObject.sizeGradients.push(serializedGradient);
  56003. }
  56004. }
  56005. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56006. if (angularSpeedGradients) {
  56007. serializationObject.angularSpeedGradients = [];
  56008. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56009. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56010. var serializedGradient = {
  56011. gradient: angularSpeedGradient.gradient,
  56012. factor1: angularSpeedGradient.factor1
  56013. };
  56014. if (angularSpeedGradient.factor2 !== undefined) {
  56015. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56016. }
  56017. serializationObject.angularSpeedGradients.push(serializedGradient);
  56018. }
  56019. }
  56020. var velocityGradients = particleSystem.getVelocityGradients();
  56021. if (velocityGradients) {
  56022. serializationObject.velocityGradients = [];
  56023. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56024. var velocityGradient = velocityGradients_1[_c];
  56025. var serializedGradient = {
  56026. gradient: velocityGradient.gradient,
  56027. factor1: velocityGradient.factor1
  56028. };
  56029. if (velocityGradient.factor2 !== undefined) {
  56030. serializedGradient.factor2 = velocityGradient.factor2;
  56031. }
  56032. serializationObject.velocityGradients.push(serializedGradient);
  56033. }
  56034. }
  56035. };
  56036. /** @hidden */
  56037. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56038. // Texture
  56039. if (parsedParticleSystem.textureName) {
  56040. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56041. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56042. }
  56043. // Emitter
  56044. if (parsedParticleSystem.emitterId === undefined) {
  56045. particleSystem.emitter = BABYLON.Vector3.Zero();
  56046. }
  56047. else if (parsedParticleSystem.emitterId) {
  56048. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56049. }
  56050. else {
  56051. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56052. }
  56053. // Misc.
  56054. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56055. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56056. }
  56057. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56058. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56059. }
  56060. // Animations
  56061. if (parsedParticleSystem.animations) {
  56062. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56063. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56064. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56065. }
  56066. }
  56067. if (parsedParticleSystem.autoAnimate) {
  56068. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56069. }
  56070. // Particle system
  56071. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56072. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56073. particleSystem.minSize = parsedParticleSystem.minSize;
  56074. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56075. if (parsedParticleSystem.minScaleX) {
  56076. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56077. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56078. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56079. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56080. }
  56081. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56082. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56083. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56084. }
  56085. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56086. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56087. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56088. }
  56089. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56090. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56091. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56092. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56093. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56094. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56095. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56096. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56097. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56098. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56099. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56100. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56101. if (parsedParticleSystem.colorGradients) {
  56102. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56103. var colorGradient = _a[_i];
  56104. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56105. }
  56106. }
  56107. if (parsedParticleSystem.sizeGradients) {
  56108. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56109. var sizeGradient = _c[_b];
  56110. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56111. }
  56112. }
  56113. if (parsedParticleSystem.angularSpeedGradients) {
  56114. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56115. var angularSpeedGradient = _e[_d];
  56116. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56117. }
  56118. }
  56119. if (parsedParticleSystem.velocityGradients) {
  56120. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56121. var velocityGradient = _g[_f];
  56122. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56123. }
  56124. }
  56125. // Emitter
  56126. var emitterType;
  56127. if (parsedParticleSystem.particleEmitterType) {
  56128. switch (parsedParticleSystem.particleEmitterType.type) {
  56129. case "SphereParticleEmitter":
  56130. emitterType = new BABYLON.SphereParticleEmitter();
  56131. break;
  56132. case "SphereDirectedParticleEmitter":
  56133. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56134. break;
  56135. case "ConeEmitter":
  56136. case "ConeParticleEmitter":
  56137. emitterType = new BABYLON.ConeParticleEmitter();
  56138. break;
  56139. case "BoxEmitter":
  56140. case "BoxParticleEmitter":
  56141. default:
  56142. emitterType = new BABYLON.BoxParticleEmitter();
  56143. break;
  56144. }
  56145. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56146. }
  56147. else {
  56148. emitterType = new BABYLON.BoxParticleEmitter();
  56149. emitterType.parse(parsedParticleSystem);
  56150. }
  56151. particleSystem.particleEmitterType = emitterType;
  56152. // Animation sheet
  56153. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56154. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56155. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56156. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56157. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56158. };
  56159. /**
  56160. * Parses a JSON object to create a particle system.
  56161. * @param parsedParticleSystem The JSON object to parse
  56162. * @param scene The scene to create the particle system in
  56163. * @param rootUrl The root url to use to load external dependencies like texture
  56164. * @returns the Parsed particle system
  56165. */
  56166. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56167. var name = parsedParticleSystem.name;
  56168. var custom = null;
  56169. var program = null;
  56170. if (parsedParticleSystem.customShader) {
  56171. program = parsedParticleSystem.customShader;
  56172. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56173. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56174. }
  56175. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56176. particleSystem.customShader = program;
  56177. if (parsedParticleSystem.id) {
  56178. particleSystem.id = parsedParticleSystem.id;
  56179. }
  56180. // Auto start
  56181. if (parsedParticleSystem.preventAutoStart) {
  56182. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56183. }
  56184. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56185. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56186. if (!particleSystem.preventAutoStart) {
  56187. particleSystem.start();
  56188. }
  56189. return particleSystem;
  56190. };
  56191. /**
  56192. * Source color is added to the destination color without alpha affecting the result.
  56193. */
  56194. ParticleSystem.BLENDMODE_ONEONE = 0;
  56195. /**
  56196. * Blend current color and particle color using particle’s alpha.
  56197. */
  56198. ParticleSystem.BLENDMODE_STANDARD = 1;
  56199. /**
  56200. * Add current color and particle color multiplied by particle’s alpha.
  56201. */
  56202. ParticleSystem.BLENDMODE_ADD = 2;
  56203. return ParticleSystem;
  56204. }());
  56205. BABYLON.ParticleSystem = ParticleSystem;
  56206. })(BABYLON || (BABYLON = {}));
  56207. //# sourceMappingURL=babylon.particleSystem.js.map
  56208. var BABYLON;
  56209. (function (BABYLON) {
  56210. /**
  56211. * Particle emitter emitting particles from the inside of a box.
  56212. * It emits the particles randomly between 2 given directions.
  56213. */
  56214. var BoxParticleEmitter = /** @class */ (function () {
  56215. /**
  56216. * Creates a new instance BoxParticleEmitter
  56217. */
  56218. function BoxParticleEmitter() {
  56219. /**
  56220. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56221. */
  56222. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56223. /**
  56224. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56225. */
  56226. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56227. /**
  56228. * 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.
  56229. */
  56230. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56231. /**
  56232. * 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.
  56233. */
  56234. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56235. }
  56236. /**
  56237. * Called by the particle System when the direction is computed for the created particle.
  56238. * @param worldMatrix is the world matrix of the particle system
  56239. * @param directionToUpdate is the direction vector to update with the result
  56240. * @param particle is the particle we are computed the direction for
  56241. */
  56242. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56243. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56244. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56245. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56246. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56247. };
  56248. /**
  56249. * Called by the particle System when the position is computed for the created particle.
  56250. * @param worldMatrix is the world matrix of the particle system
  56251. * @param positionToUpdate is the position vector to update with the result
  56252. * @param particle is the particle we are computed the position for
  56253. */
  56254. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56255. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56256. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56257. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56259. };
  56260. /**
  56261. * Clones the current emitter and returns a copy of it
  56262. * @returns the new emitter
  56263. */
  56264. BoxParticleEmitter.prototype.clone = function () {
  56265. var newOne = new BoxParticleEmitter();
  56266. BABYLON.Tools.DeepCopy(this, newOne);
  56267. return newOne;
  56268. };
  56269. /**
  56270. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56271. * @param effect defines the update shader
  56272. */
  56273. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56274. effect.setVector3("direction1", this.direction1);
  56275. effect.setVector3("direction2", this.direction2);
  56276. effect.setVector3("minEmitBox", this.minEmitBox);
  56277. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56278. };
  56279. /**
  56280. * Returns a string to use to update the GPU particles update shader
  56281. * @returns a string containng the defines string
  56282. */
  56283. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56284. return "#define BOXEMITTER";
  56285. };
  56286. /**
  56287. * Returns the string "BoxParticleEmitter"
  56288. * @returns a string containing the class name
  56289. */
  56290. BoxParticleEmitter.prototype.getClassName = function () {
  56291. return "BoxParticleEmitter";
  56292. };
  56293. /**
  56294. * Serializes the particle system to a JSON object.
  56295. * @returns the JSON object
  56296. */
  56297. BoxParticleEmitter.prototype.serialize = function () {
  56298. var serializationObject = {};
  56299. serializationObject.type = this.getClassName();
  56300. serializationObject.direction1 = this.direction1.asArray();
  56301. serializationObject.direction2 = this.direction2.asArray();
  56302. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56303. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56304. return serializationObject;
  56305. };
  56306. /**
  56307. * Parse properties from a JSON object
  56308. * @param serializationObject defines the JSON object
  56309. */
  56310. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56311. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56312. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56313. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56314. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56315. };
  56316. return BoxParticleEmitter;
  56317. }());
  56318. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56319. })(BABYLON || (BABYLON = {}));
  56320. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56321. var BABYLON;
  56322. (function (BABYLON) {
  56323. /**
  56324. * Particle emitter emitting particles from the inside of a cone.
  56325. * It emits the particles alongside the cone volume from the base to the particle.
  56326. * The emission direction might be randomized.
  56327. */
  56328. var ConeParticleEmitter = /** @class */ (function () {
  56329. /**
  56330. * Creates a new instance ConeParticleEmitter
  56331. * @param radius the radius of the emission cone (1 by default)
  56332. * @param angles the cone base angle (PI by default)
  56333. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56334. */
  56335. function ConeParticleEmitter(radius, angle,
  56336. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56337. directionRandomizer) {
  56338. if (radius === void 0) { radius = 1; }
  56339. if (angle === void 0) { angle = Math.PI; }
  56340. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56341. this.directionRandomizer = directionRandomizer;
  56342. /**
  56343. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56344. */
  56345. this.radiusRange = 1;
  56346. /**
  56347. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56348. */
  56349. this.heightRange = 1;
  56350. this.angle = angle;
  56351. this.radius = radius;
  56352. }
  56353. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56354. /**
  56355. * Gets or sets the radius of the emission cone
  56356. */
  56357. get: function () {
  56358. return this._radius;
  56359. },
  56360. set: function (value) {
  56361. this._radius = value;
  56362. this._buildHeight();
  56363. },
  56364. enumerable: true,
  56365. configurable: true
  56366. });
  56367. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56368. /**
  56369. * Gets or sets the angle of the emission cone
  56370. */
  56371. get: function () {
  56372. return this._angle;
  56373. },
  56374. set: function (value) {
  56375. this._angle = value;
  56376. this._buildHeight();
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. ConeParticleEmitter.prototype._buildHeight = function () {
  56382. if (this._angle !== 0) {
  56383. this._height = this._radius / Math.tan(this._angle / 2);
  56384. }
  56385. else {
  56386. this._height = 1;
  56387. }
  56388. };
  56389. /**
  56390. * Called by the particle System when the direction is computed for the created particle.
  56391. * @param worldMatrix is the world matrix of the particle system
  56392. * @param directionToUpdate is the direction vector to update with the result
  56393. * @param particle is the particle we are computed the direction for
  56394. */
  56395. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56396. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56397. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56398. }
  56399. else {
  56400. // measure the direction Vector from the emitter to the particle.
  56401. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56402. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56403. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56404. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56405. direction.x += randX;
  56406. direction.y += randY;
  56407. direction.z += randZ;
  56408. direction.normalize();
  56409. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56410. }
  56411. };
  56412. /**
  56413. * Called by the particle System when the position is computed for the created particle.
  56414. * @param worldMatrix is the world matrix of the particle system
  56415. * @param positionToUpdate is the position vector to update with the result
  56416. * @param particle is the particle we are computed the position for
  56417. */
  56418. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56419. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56420. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56421. // Better distribution in a cone at normal angles.
  56422. h = 1 - h * h;
  56423. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56424. radius = radius * h;
  56425. var randX = radius * Math.sin(s);
  56426. var randZ = radius * Math.cos(s);
  56427. var randY = h * this._height;
  56428. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56429. };
  56430. /**
  56431. * Clones the current emitter and returns a copy of it
  56432. * @returns the new emitter
  56433. */
  56434. ConeParticleEmitter.prototype.clone = function () {
  56435. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56436. BABYLON.Tools.DeepCopy(this, newOne);
  56437. return newOne;
  56438. };
  56439. /**
  56440. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56441. * @param effect defines the update shader
  56442. */
  56443. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56444. effect.setFloat2("radius", this._radius, this.radiusRange);
  56445. effect.setFloat("coneAngle", this._angle);
  56446. effect.setFloat2("height", this._height, this.heightRange);
  56447. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56448. };
  56449. /**
  56450. * Returns a string to use to update the GPU particles update shader
  56451. * @returns a string containng the defines string
  56452. */
  56453. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56454. return "#define CONEEMITTER";
  56455. };
  56456. /**
  56457. * Returns the string "ConeParticleEmitter"
  56458. * @returns a string containing the class name
  56459. */
  56460. ConeParticleEmitter.prototype.getClassName = function () {
  56461. return "ConeParticleEmitter";
  56462. };
  56463. /**
  56464. * Serializes the particle system to a JSON object.
  56465. * @returns the JSON object
  56466. */
  56467. ConeParticleEmitter.prototype.serialize = function () {
  56468. var serializationObject = {};
  56469. serializationObject.type = this.getClassName();
  56470. serializationObject.radius = this._radius;
  56471. serializationObject.angle = this._angle;
  56472. serializationObject.directionRandomizer = this.directionRandomizer;
  56473. return serializationObject;
  56474. };
  56475. /**
  56476. * Parse properties from a JSON object
  56477. * @param serializationObject defines the JSON object
  56478. */
  56479. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56480. this.radius = serializationObject.radius;
  56481. this.angle = serializationObject.angle;
  56482. this.directionRandomizer = serializationObject.directionRandomizer;
  56483. };
  56484. return ConeParticleEmitter;
  56485. }());
  56486. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56487. })(BABYLON || (BABYLON = {}));
  56488. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56489. var BABYLON;
  56490. (function (BABYLON) {
  56491. /**
  56492. * Particle emitter emitting particles from the inside of a sphere.
  56493. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56494. */
  56495. var SphereParticleEmitter = /** @class */ (function () {
  56496. /**
  56497. * Creates a new instance SphereParticleEmitter
  56498. * @param radius the radius of the emission sphere (1 by default)
  56499. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56500. */
  56501. function SphereParticleEmitter(
  56502. /**
  56503. * The radius of the emission sphere.
  56504. */
  56505. radius,
  56506. /**
  56507. * How much to randomize the particle direction [0-1].
  56508. */
  56509. directionRandomizer) {
  56510. if (radius === void 0) { radius = 1; }
  56511. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56512. this.radius = radius;
  56513. this.directionRandomizer = directionRandomizer;
  56514. /**
  56515. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56516. */
  56517. this.radiusRange = 1;
  56518. }
  56519. /**
  56520. * Called by the particle System when the direction is computed for the created particle.
  56521. * @param worldMatrix is the world matrix of the particle system
  56522. * @param directionToUpdate is the direction vector to update with the result
  56523. * @param particle is the particle we are computed the direction for
  56524. */
  56525. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56526. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56527. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56528. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56529. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56530. direction.x += randX;
  56531. direction.y += randY;
  56532. direction.z += randZ;
  56533. direction.normalize();
  56534. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56535. };
  56536. /**
  56537. * Called by the particle System when the position is computed for the created particle.
  56538. * @param worldMatrix is the world matrix of the particle system
  56539. * @param positionToUpdate is the position vector to update with the result
  56540. * @param particle is the particle we are computed the position for
  56541. */
  56542. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56543. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56544. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56545. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56546. var theta = Math.acos(2 * v - 1);
  56547. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56548. var randY = randRadius * Math.cos(theta);
  56549. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56551. };
  56552. /**
  56553. * Clones the current emitter and returns a copy of it
  56554. * @returns the new emitter
  56555. */
  56556. SphereParticleEmitter.prototype.clone = function () {
  56557. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56558. BABYLON.Tools.DeepCopy(this, newOne);
  56559. return newOne;
  56560. };
  56561. /**
  56562. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56563. * @param effect defines the update shader
  56564. */
  56565. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56566. effect.setFloat("radius", this.radius);
  56567. effect.setFloat("radiusRange", this.radiusRange);
  56568. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56569. };
  56570. /**
  56571. * Returns a string to use to update the GPU particles update shader
  56572. * @returns a string containng the defines string
  56573. */
  56574. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56575. return "#define SPHEREEMITTER";
  56576. };
  56577. /**
  56578. * Returns the string "SphereParticleEmitter"
  56579. * @returns a string containing the class name
  56580. */
  56581. SphereParticleEmitter.prototype.getClassName = function () {
  56582. return "SphereParticleEmitter";
  56583. };
  56584. /**
  56585. * Serializes the particle system to a JSON object.
  56586. * @returns the JSON object
  56587. */
  56588. SphereParticleEmitter.prototype.serialize = function () {
  56589. var serializationObject = {};
  56590. serializationObject.type = this.getClassName();
  56591. serializationObject.radius = this.radius;
  56592. serializationObject.radiusRange = this.radiusRange;
  56593. serializationObject.directionRandomizer = this.directionRandomizer;
  56594. return serializationObject;
  56595. };
  56596. /**
  56597. * Parse properties from a JSON object
  56598. * @param serializationObject defines the JSON object
  56599. */
  56600. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56601. this.radius = serializationObject.radius;
  56602. this.radiusRange = serializationObject.radiusRange;
  56603. this.directionRandomizer = serializationObject.directionRandomizer;
  56604. };
  56605. return SphereParticleEmitter;
  56606. }());
  56607. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56608. /**
  56609. * Particle emitter emitting particles from the inside of a sphere.
  56610. * It emits the particles randomly between two vectors.
  56611. */
  56612. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56613. __extends(SphereDirectedParticleEmitter, _super);
  56614. /**
  56615. * Creates a new instance SphereDirectedParticleEmitter
  56616. * @param radius the radius of the emission sphere (1 by default)
  56617. * @param direction1 the min limit of the emission direction (up vector by default)
  56618. * @param direction2 the max limit of the emission direction (up vector by default)
  56619. */
  56620. function SphereDirectedParticleEmitter(radius,
  56621. /**
  56622. * The min limit of the emission direction.
  56623. */
  56624. direction1,
  56625. /**
  56626. * The max limit of the emission direction.
  56627. */
  56628. direction2) {
  56629. if (radius === void 0) { radius = 1; }
  56630. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56631. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56632. var _this = _super.call(this, radius) || this;
  56633. _this.direction1 = direction1;
  56634. _this.direction2 = direction2;
  56635. return _this;
  56636. }
  56637. /**
  56638. * Called by the particle System when the direction is computed for the created particle.
  56639. * @param worldMatrix is the world matrix of the particle system
  56640. * @param directionToUpdate is the direction vector to update with the result
  56641. * @param particle is the particle we are computed the direction for
  56642. */
  56643. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56644. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56645. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56646. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56647. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56648. };
  56649. /**
  56650. * Clones the current emitter and returns a copy of it
  56651. * @returns the new emitter
  56652. */
  56653. SphereDirectedParticleEmitter.prototype.clone = function () {
  56654. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56655. BABYLON.Tools.DeepCopy(this, newOne);
  56656. return newOne;
  56657. };
  56658. /**
  56659. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56660. * @param effect defines the update shader
  56661. */
  56662. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56663. effect.setFloat("radius", this.radius);
  56664. effect.setFloat("radiusRange", this.radiusRange);
  56665. effect.setVector3("direction1", this.direction1);
  56666. effect.setVector3("direction2", this.direction2);
  56667. };
  56668. /**
  56669. * Returns a string to use to update the GPU particles update shader
  56670. * @returns a string containng the defines string
  56671. */
  56672. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56673. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56674. };
  56675. /**
  56676. * Returns the string "SphereDirectedParticleEmitter"
  56677. * @returns a string containing the class name
  56678. */
  56679. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56680. return "SphereDirectedParticleEmitter";
  56681. };
  56682. /**
  56683. * Serializes the particle system to a JSON object.
  56684. * @returns the JSON object
  56685. */
  56686. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56687. var serializationObject = _super.prototype.serialize.call(this);
  56688. serializationObject.direction1 = this.direction1.asArray();
  56689. serializationObject.direction2 = this.direction2.asArray();
  56690. return serializationObject;
  56691. };
  56692. /**
  56693. * Parse properties from a JSON object
  56694. * @param serializationObject defines the JSON object
  56695. */
  56696. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56697. _super.prototype.parse.call(this, serializationObject);
  56698. this.direction1.copyFrom(serializationObject.direction1);
  56699. this.direction2.copyFrom(serializationObject.direction2);
  56700. };
  56701. return SphereDirectedParticleEmitter;
  56702. }(SphereParticleEmitter));
  56703. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56704. })(BABYLON || (BABYLON = {}));
  56705. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. // Adds the parsers to the scene parsers.
  56709. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  56710. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  56711. if (!individualParser) {
  56712. return;
  56713. }
  56714. // Particles Systems
  56715. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56716. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56717. var parsedParticleSystem = parsedData.particleSystems[index];
  56718. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  56719. }
  56720. }
  56721. });
  56722. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  56723. if (parsedParticleSystem.activeParticleCount) {
  56724. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56725. return ps;
  56726. }
  56727. else {
  56728. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56729. return ps;
  56730. }
  56731. });
  56732. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  56733. if (uniformsNames === void 0) { uniformsNames = []; }
  56734. if (samplers === void 0) { samplers = []; }
  56735. if (defines === void 0) { defines = ""; }
  56736. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  56737. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  56738. if (defines.indexOf(" BILLBOARD") === -1) {
  56739. defines += "\n#define BILLBOARD\n";
  56740. }
  56741. if (samplers.indexOf("diffuseSampler") === -1) {
  56742. samplers.push("diffuseSampler");
  56743. }
  56744. return this.createEffect({
  56745. vertex: "particles",
  56746. fragmentElement: fragmentName
  56747. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  56748. };
  56749. })(BABYLON || (BABYLON = {}));
  56750. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  56751. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56752. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56753. s = arguments[i];
  56754. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56755. t[p] = s[p];
  56756. }
  56757. return t;
  56758. };
  56759. var BABYLON;
  56760. (function (BABYLON) {
  56761. /**
  56762. * This represents a GPU particle system in Babylon
  56763. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56764. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56765. */
  56766. var GPUParticleSystem = /** @class */ (function () {
  56767. /**
  56768. * Instantiates a GPU particle system.
  56769. * 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.
  56770. * @param name The name of the particle system
  56771. * @param options The options used to create the system
  56772. * @param scene The scene the particle system belongs to
  56773. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56774. */
  56775. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  56776. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56777. /**
  56778. * The emitter represents the Mesh or position we are attaching the particle system to.
  56779. */
  56780. this.emitter = null;
  56781. /**
  56782. * The rendering group used by the Particle system to chose when to render.
  56783. */
  56784. this.renderingGroupId = 0;
  56785. /**
  56786. * The layer mask we are rendering the particles through.
  56787. */
  56788. this.layerMask = 0x0FFFFFFF;
  56789. this._accumulatedCount = 0;
  56790. this._targetIndex = 0;
  56791. this._currentRenderId = -1;
  56792. this._started = false;
  56793. this._stopped = false;
  56794. this._timeDelta = 0;
  56795. this._attributesStrideSize = 21;
  56796. this._actualFrame = 0;
  56797. this._rawTextureWidth = 256;
  56798. /**
  56799. * List of animations used by the particle system.
  56800. */
  56801. this.animations = [];
  56802. /**
  56803. * An event triggered when the system is disposed.
  56804. */
  56805. this.onDisposeObservable = new BABYLON.Observable();
  56806. /**
  56807. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56808. */
  56809. this.updateSpeed = 0.01;
  56810. /**
  56811. * The amount of time the particle system is running (depends of the overall update speed).
  56812. */
  56813. this.targetStopDuration = 0;
  56814. /**
  56815. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56816. */
  56817. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56818. /**
  56819. * Minimum life time of emitting particles.
  56820. */
  56821. this.minLifeTime = 1;
  56822. /**
  56823. * Maximum life time of emitting particles.
  56824. */
  56825. this.maxLifeTime = 1;
  56826. /**
  56827. * Minimum Size of emitting particles.
  56828. */
  56829. this.minSize = 1;
  56830. /**
  56831. * Maximum Size of emitting particles.
  56832. */
  56833. this.maxSize = 1;
  56834. /**
  56835. * Minimum scale of emitting particles on X axis.
  56836. */
  56837. this.minScaleX = 1;
  56838. /**
  56839. * Maximum scale of emitting particles on X axis.
  56840. */
  56841. this.maxScaleX = 1;
  56842. /**
  56843. * Minimum scale of emitting particles on Y axis.
  56844. */
  56845. this.minScaleY = 1;
  56846. /**
  56847. * Maximum scale of emitting particles on Y axis.
  56848. */
  56849. this.maxScaleY = 1;
  56850. /**
  56851. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56852. */
  56853. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56854. /**
  56855. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56856. */
  56857. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56858. /**
  56859. * Color the particle will have at the end of its lifetime.
  56860. */
  56861. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56862. /**
  56863. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56864. */
  56865. this.emitRate = 100;
  56866. /**
  56867. * You can use gravity if you want to give an orientation to your particles.
  56868. */
  56869. this.gravity = BABYLON.Vector3.Zero();
  56870. /**
  56871. * Minimum power of emitting particles.
  56872. */
  56873. this.minEmitPower = 1;
  56874. /**
  56875. * Maximum power of emitting particles.
  56876. */
  56877. this.maxEmitPower = 1;
  56878. /**
  56879. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56880. */
  56881. this.minAngularSpeed = 0;
  56882. /**
  56883. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56884. */
  56885. this.maxAngularSpeed = 0;
  56886. /**
  56887. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56888. * to override the particles.
  56889. */
  56890. this.forceDepthWrite = false;
  56891. this._preWarmDone = false;
  56892. /** 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 */
  56893. this.preWarmCycles = 0;
  56894. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56895. this.preWarmStepOffset = 1;
  56896. /**
  56897. * Gets or sets the minimal initial rotation in radians.
  56898. */
  56899. this.minInitialRotation = 0;
  56900. /**
  56901. * Gets or sets the maximal initial rotation in radians.
  56902. */
  56903. this.maxInitialRotation = 0;
  56904. /**
  56905. * 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)
  56906. */
  56907. this.spriteCellChangeSpeed = 1;
  56908. /**
  56909. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56910. */
  56911. this.startSpriteCellID = 0;
  56912. /**
  56913. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56914. */
  56915. this.endSpriteCellID = 0;
  56916. /**
  56917. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56918. */
  56919. this.spriteCellWidth = 0;
  56920. /**
  56921. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56922. */
  56923. this.spriteCellHeight = 0;
  56924. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56925. this.translationPivot = new BABYLON.Vector2(0, 0);
  56926. /**
  56927. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56928. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  56929. */
  56930. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56931. this._isBillboardBased = true;
  56932. this._colorGradients = null;
  56933. this._angularSpeedGradients = null;
  56934. this._sizeGradients = null;
  56935. this._velocityGradients = null;
  56936. this.id = name;
  56937. this.name = name;
  56938. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56939. this._engine = this._scene.getEngine();
  56940. if (!options.randomTextureSize) {
  56941. delete options.randomTextureSize;
  56942. }
  56943. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56944. var optionsAsNumber = options;
  56945. if (isFinite(optionsAsNumber)) {
  56946. fullOptions.capacity = optionsAsNumber;
  56947. }
  56948. this._capacity = fullOptions.capacity;
  56949. this._activeCount = fullOptions.capacity;
  56950. this._currentActiveCount = 0;
  56951. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56952. this._scene.particleSystems.push(this);
  56953. this._updateEffectOptions = {
  56954. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  56955. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56956. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56957. "angleRange", "radiusRange", "cellInfos"],
  56958. uniformBuffersNames: [],
  56959. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  56960. defines: "",
  56961. fallbacks: null,
  56962. onCompiled: null,
  56963. onError: null,
  56964. indexParameters: null,
  56965. maxSimultaneousLights: 0,
  56966. transformFeedbackVaryings: []
  56967. };
  56968. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56969. // Random data
  56970. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56971. var d = [];
  56972. for (var i = 0; i < maxTextureSize; ++i) {
  56973. d.push(Math.random());
  56974. d.push(Math.random());
  56975. d.push(Math.random());
  56976. d.push(Math.random());
  56977. }
  56978. 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);
  56979. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56980. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56981. d = [];
  56982. for (var i = 0; i < maxTextureSize; ++i) {
  56983. d.push(Math.random());
  56984. d.push(Math.random());
  56985. d.push(Math.random());
  56986. d.push(Math.random());
  56987. }
  56988. 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);
  56989. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56990. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56991. this._randomTextureSize = maxTextureSize;
  56992. }
  56993. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56994. /**
  56995. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56996. */
  56997. get: function () {
  56998. if (!BABYLON.Engine.LastCreatedEngine) {
  56999. return false;
  57000. }
  57001. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57002. },
  57003. enumerable: true,
  57004. configurable: true
  57005. });
  57006. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57007. /**
  57008. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57009. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57010. */
  57011. get: function () {
  57012. if (this.particleEmitterType.direction1) {
  57013. return this.particleEmitterType.direction1;
  57014. }
  57015. return BABYLON.Vector3.Zero();
  57016. },
  57017. set: function (value) {
  57018. if (this.particleEmitterType.direction1) {
  57019. this.particleEmitterType.direction1 = value;
  57020. }
  57021. },
  57022. enumerable: true,
  57023. configurable: true
  57024. });
  57025. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57026. /**
  57027. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57028. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57029. */
  57030. get: function () {
  57031. if (this.particleEmitterType.direction2) {
  57032. return this.particleEmitterType.direction2;
  57033. }
  57034. return BABYLON.Vector3.Zero();
  57035. },
  57036. set: function (value) {
  57037. if (this.particleEmitterType.direction2) {
  57038. this.particleEmitterType.direction2 = value;
  57039. }
  57040. },
  57041. enumerable: true,
  57042. configurable: true
  57043. });
  57044. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57045. /**
  57046. * 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.
  57047. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57048. */
  57049. get: function () {
  57050. if (this.particleEmitterType.minEmitBox) {
  57051. return this.particleEmitterType.minEmitBox;
  57052. }
  57053. return BABYLON.Vector3.Zero();
  57054. },
  57055. set: function (value) {
  57056. if (this.particleEmitterType.minEmitBox) {
  57057. this.particleEmitterType.minEmitBox = value;
  57058. }
  57059. },
  57060. enumerable: true,
  57061. configurable: true
  57062. });
  57063. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57064. /**
  57065. * 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.
  57066. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57067. */
  57068. get: function () {
  57069. if (this.particleEmitterType.maxEmitBox) {
  57070. return this.particleEmitterType.maxEmitBox;
  57071. }
  57072. return BABYLON.Vector3.Zero();
  57073. },
  57074. set: function (value) {
  57075. if (this.particleEmitterType.maxEmitBox) {
  57076. this.particleEmitterType.maxEmitBox = value;
  57077. }
  57078. },
  57079. enumerable: true,
  57080. configurable: true
  57081. });
  57082. /**
  57083. * Gets the maximum number of particles active at the same time.
  57084. * @returns The max number of active particles.
  57085. */
  57086. GPUParticleSystem.prototype.getCapacity = function () {
  57087. return this._capacity;
  57088. };
  57089. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57090. /**
  57091. * Gets or set the number of active particles
  57092. */
  57093. get: function () {
  57094. return this._activeCount;
  57095. },
  57096. set: function (value) {
  57097. this._activeCount = Math.min(value, this._capacity);
  57098. },
  57099. enumerable: true,
  57100. configurable: true
  57101. });
  57102. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57103. /**
  57104. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57105. */
  57106. get: function () {
  57107. return this._isAnimationSheetEnabled;
  57108. },
  57109. enumerable: true,
  57110. configurable: true
  57111. });
  57112. /**
  57113. * Is this system ready to be used/rendered
  57114. * @return true if the system is ready
  57115. */
  57116. GPUParticleSystem.prototype.isReady = function () {
  57117. if (!this._updateEffect) {
  57118. this._recreateUpdateEffect();
  57119. this._recreateRenderEffect();
  57120. return false;
  57121. }
  57122. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57123. return false;
  57124. }
  57125. return true;
  57126. };
  57127. /**
  57128. * Gets Wether the system has been started.
  57129. * @returns True if it has been started, otherwise false.
  57130. */
  57131. GPUParticleSystem.prototype.isStarted = function () {
  57132. return this._started;
  57133. };
  57134. /**
  57135. * Starts the particle system and begins to emit.
  57136. */
  57137. GPUParticleSystem.prototype.start = function () {
  57138. this._started = true;
  57139. this._stopped = false;
  57140. this._preWarmDone = false;
  57141. };
  57142. /**
  57143. * Stops the particle system.
  57144. */
  57145. GPUParticleSystem.prototype.stop = function () {
  57146. this._stopped = true;
  57147. };
  57148. /**
  57149. * Remove all active particles
  57150. */
  57151. GPUParticleSystem.prototype.reset = function () {
  57152. this._releaseBuffers();
  57153. this._releaseVAOs();
  57154. this._currentActiveCount = 0;
  57155. this._targetIndex = 0;
  57156. };
  57157. /**
  57158. * Returns the string "GPUParticleSystem"
  57159. * @returns a string containing the class name
  57160. */
  57161. GPUParticleSystem.prototype.getClassName = function () {
  57162. return "GPUParticleSystem";
  57163. };
  57164. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57165. /**
  57166. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57167. */
  57168. get: function () {
  57169. return this._isBillboardBased;
  57170. },
  57171. set: function (value) {
  57172. if (this._isBillboardBased === value) {
  57173. return;
  57174. }
  57175. this._isBillboardBased = value;
  57176. this._releaseBuffers();
  57177. },
  57178. enumerable: true,
  57179. configurable: true
  57180. });
  57181. /**
  57182. * Gets the current list of color gradients.
  57183. * You must use addColorGradient and removeColorGradient to udpate this list
  57184. * @returns the list of color gradients
  57185. */
  57186. GPUParticleSystem.prototype.getColorGradients = function () {
  57187. return this._colorGradients;
  57188. };
  57189. /**
  57190. * Gets the current list of size gradients.
  57191. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57192. * @returns the list of size gradients
  57193. */
  57194. GPUParticleSystem.prototype.getSizeGradients = function () {
  57195. return this._sizeGradients;
  57196. };
  57197. /**
  57198. * Gets the current list of angular speed gradients.
  57199. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57200. * @returns the list of angular speed gradients
  57201. */
  57202. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57203. return this._angularSpeedGradients;
  57204. };
  57205. /**
  57206. * Gets the current list of velocity gradients.
  57207. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57208. * @returns the list of angular speed gradients
  57209. */
  57210. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57211. return this._velocityGradients;
  57212. };
  57213. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57214. if (!gradients) {
  57215. return this;
  57216. }
  57217. var index = 0;
  57218. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57219. var valueGradient = gradients_1[_i];
  57220. if (valueGradient.gradient === gradient) {
  57221. gradients.splice(index, 1);
  57222. break;
  57223. }
  57224. index++;
  57225. }
  57226. if (texture) {
  57227. texture.dispose();
  57228. }
  57229. this._releaseBuffers();
  57230. return this;
  57231. };
  57232. /**
  57233. * Adds a new color gradient
  57234. * @param gradient defines the gradient to use (between 0 and 1)
  57235. * @param color defines the color to affect to the specified gradient
  57236. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57237. * @returns the current particle system
  57238. */
  57239. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57240. if (!this._colorGradients) {
  57241. this._colorGradients = [];
  57242. }
  57243. var colorGradient = new BABYLON.ColorGradient();
  57244. colorGradient.gradient = gradient;
  57245. colorGradient.color1 = color1;
  57246. this._colorGradients.push(colorGradient);
  57247. this._colorGradients.sort(function (a, b) {
  57248. if (a.gradient < b.gradient) {
  57249. return -1;
  57250. }
  57251. else if (a.gradient > b.gradient) {
  57252. return 1;
  57253. }
  57254. return 0;
  57255. });
  57256. if (this._colorGradientsTexture) {
  57257. this._colorGradientsTexture.dispose();
  57258. this._colorGradientsTexture = null;
  57259. }
  57260. this._releaseBuffers();
  57261. return this;
  57262. };
  57263. /**
  57264. * Remove a specific color gradient
  57265. * @param gradient defines the gradient to remove
  57266. * @returns the current particle system
  57267. */
  57268. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57269. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57270. this._colorGradientsTexture = null;
  57271. return this;
  57272. };
  57273. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57274. var valueGradient = new BABYLON.FactorGradient();
  57275. valueGradient.gradient = gradient;
  57276. valueGradient.factor1 = factor;
  57277. factorGradients.push(valueGradient);
  57278. factorGradients.sort(function (a, b) {
  57279. if (a.gradient < b.gradient) {
  57280. return -1;
  57281. }
  57282. else if (a.gradient > b.gradient) {
  57283. return 1;
  57284. }
  57285. return 0;
  57286. });
  57287. this._releaseBuffers();
  57288. };
  57289. /**
  57290. * Adds a new size gradient
  57291. * @param gradient defines the gradient to use (between 0 and 1)
  57292. * @param factor defines the size factor to affect to the specified gradient
  57293. * @returns the current particle system
  57294. */
  57295. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57296. if (!this._sizeGradients) {
  57297. this._sizeGradients = [];
  57298. }
  57299. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57300. if (this._sizeGradientsTexture) {
  57301. this._sizeGradientsTexture.dispose();
  57302. this._sizeGradientsTexture = null;
  57303. }
  57304. this._releaseBuffers();
  57305. return this;
  57306. };
  57307. /**
  57308. * Remove a specific size gradient
  57309. * @param gradient defines the gradient to remove
  57310. * @returns the current particle system
  57311. */
  57312. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57313. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57314. this._sizeGradientsTexture = null;
  57315. return this;
  57316. };
  57317. /**
  57318. * Adds a new angular speed gradient
  57319. * @param gradient defines the gradient to use (between 0 and 1)
  57320. * @param factor defines the size factor to affect to the specified gradient
  57321. * @returns the current particle system
  57322. */
  57323. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57324. if (!this._angularSpeedGradients) {
  57325. this._angularSpeedGradients = [];
  57326. }
  57327. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57328. if (this._angularSpeedGradientsTexture) {
  57329. this._angularSpeedGradientsTexture.dispose();
  57330. this._angularSpeedGradientsTexture = null;
  57331. }
  57332. this._releaseBuffers();
  57333. return this;
  57334. };
  57335. /**
  57336. * Remove a specific angular speed gradient
  57337. * @param gradient defines the gradient to remove
  57338. * @returns the current particle system
  57339. */
  57340. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57341. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57342. this._angularSpeedGradientsTexture = null;
  57343. return this;
  57344. };
  57345. /**
  57346. * Adds a new velocity gradient
  57347. * @param gradient defines the gradient to use (between 0 and 1)
  57348. * @param factor defines the size factor to affect to the specified gradient
  57349. * @returns the current particle system
  57350. */
  57351. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57352. if (!this._velocityGradients) {
  57353. this._velocityGradients = [];
  57354. }
  57355. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57356. if (this._velocityGradientsTexture) {
  57357. this._velocityGradientsTexture.dispose();
  57358. this._velocityGradientsTexture = null;
  57359. }
  57360. this._releaseBuffers();
  57361. return this;
  57362. };
  57363. /**
  57364. * Remove a specific velocity gradient
  57365. * @param gradient defines the gradient to remove
  57366. * @returns the current particle system
  57367. */
  57368. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57369. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57370. this._velocityGradientsTexture = null;
  57371. return this;
  57372. };
  57373. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57374. var updateVertexBuffers = {};
  57375. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57376. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57377. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57378. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57379. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57380. var offset = 12;
  57381. if (!this._colorGradientsTexture) {
  57382. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57383. offset += 4;
  57384. }
  57385. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57386. offset += 3;
  57387. if (!this._isBillboardBased) {
  57388. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57389. offset += 3;
  57390. }
  57391. if (this._angularSpeedGradientsTexture) {
  57392. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57393. offset += 1;
  57394. }
  57395. else {
  57396. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57397. offset += 2;
  57398. }
  57399. if (this._isAnimationSheetEnabled) {
  57400. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57401. offset += 1;
  57402. }
  57403. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57404. this._engine.bindArrayBuffer(null);
  57405. return vao;
  57406. };
  57407. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57408. var renderVertexBuffers = {};
  57409. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57410. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57411. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57412. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57413. var offset = 12;
  57414. if (!this._colorGradientsTexture) {
  57415. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57416. offset += 4;
  57417. }
  57418. offset += 3; // Direction
  57419. if (!this._isBillboardBased) {
  57420. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57421. offset += 3;
  57422. }
  57423. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57424. if (this._angularSpeedGradientsTexture) {
  57425. offset++;
  57426. }
  57427. else {
  57428. offset += 2;
  57429. }
  57430. if (this._isAnimationSheetEnabled) {
  57431. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57432. offset += 1;
  57433. }
  57434. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57435. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57436. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57437. this._engine.bindArrayBuffer(null);
  57438. return vao;
  57439. };
  57440. GPUParticleSystem.prototype._initialize = function (force) {
  57441. if (force === void 0) { force = false; }
  57442. if (this._buffer0 && !force) {
  57443. return;
  57444. }
  57445. var engine = this._scene.getEngine();
  57446. var data = new Array();
  57447. if (!this.isBillboardBased) {
  57448. this._attributesStrideSize += 3;
  57449. }
  57450. if (this._colorGradientsTexture) {
  57451. this._attributesStrideSize -= 4;
  57452. }
  57453. if (this._angularSpeedGradientsTexture) {
  57454. this._attributesStrideSize -= 1;
  57455. }
  57456. if (this._isAnimationSheetEnabled) {
  57457. this._attributesStrideSize += 1;
  57458. }
  57459. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57460. // position
  57461. data.push(0.0);
  57462. data.push(0.0);
  57463. data.push(0.0);
  57464. // Age and life
  57465. data.push(0.0); // create the particle as a dead one to create a new one at start
  57466. data.push(0.0);
  57467. // Seed
  57468. data.push(Math.random());
  57469. data.push(Math.random());
  57470. data.push(Math.random());
  57471. data.push(Math.random());
  57472. // Size
  57473. data.push(0.0);
  57474. data.push(0.0);
  57475. data.push(0.0);
  57476. if (!this._colorGradientsTexture) {
  57477. // color
  57478. data.push(0.0);
  57479. data.push(0.0);
  57480. data.push(0.0);
  57481. data.push(0.0);
  57482. }
  57483. // direction
  57484. data.push(0.0);
  57485. data.push(0.0);
  57486. data.push(0.0);
  57487. if (!this.isBillboardBased) {
  57488. // initialDirection
  57489. data.push(0.0);
  57490. data.push(0.0);
  57491. data.push(0.0);
  57492. }
  57493. // angle
  57494. data.push(0.0);
  57495. if (!this._angularSpeedGradientsTexture) {
  57496. data.push(0.0);
  57497. }
  57498. if (this._isAnimationSheetEnabled) {
  57499. data.push(0.0);
  57500. }
  57501. }
  57502. // Sprite data
  57503. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57504. -0.5, 0.5, 0, 1,
  57505. -0.5, -0.5, 0, 0,
  57506. 0.5, -0.5, 1, 0]);
  57507. // Buffers
  57508. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57509. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57510. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57511. // Update VAO
  57512. this._updateVAO = [];
  57513. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57514. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57515. // Render VAO
  57516. this._renderVAO = [];
  57517. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57518. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57519. // Links
  57520. this._sourceBuffer = this._buffer0;
  57521. this._targetBuffer = this._buffer1;
  57522. };
  57523. /** @hidden */
  57524. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57525. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57526. if (this._isBillboardBased) {
  57527. defines += "\n#define BILLBOARD";
  57528. }
  57529. if (this._colorGradientsTexture) {
  57530. defines += "\n#define COLORGRADIENTS";
  57531. }
  57532. if (this._sizeGradientsTexture) {
  57533. defines += "\n#define SIZEGRADIENTS";
  57534. }
  57535. if (this._angularSpeedGradientsTexture) {
  57536. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57537. }
  57538. if (this._velocityGradientsTexture) {
  57539. defines += "\n#define VELOCITYGRADIENTS";
  57540. }
  57541. if (this.isAnimationSheetEnabled) {
  57542. defines += "\n#define ANIMATESHEET";
  57543. }
  57544. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57545. return;
  57546. }
  57547. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57548. if (!this._colorGradientsTexture) {
  57549. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57550. }
  57551. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57552. if (!this._isBillboardBased) {
  57553. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57554. }
  57555. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57556. if (this.isAnimationSheetEnabled) {
  57557. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57558. }
  57559. this._updateEffectOptions.defines = defines;
  57560. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57561. };
  57562. /** @hidden */
  57563. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57564. var defines = "";
  57565. if (this._scene.clipPlane) {
  57566. defines = "\n#define CLIPPLANE";
  57567. }
  57568. if (this._isBillboardBased) {
  57569. defines += "\n#define BILLBOARD";
  57570. switch (this.billboardMode) {
  57571. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57572. defines += "\n#define BILLBOARDY";
  57573. break;
  57574. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57575. default:
  57576. break;
  57577. }
  57578. }
  57579. if (this._colorGradientsTexture) {
  57580. defines += "\n#define COLORGRADIENTS";
  57581. }
  57582. if (this.isAnimationSheetEnabled) {
  57583. defines += "\n#define ANIMATESHEET";
  57584. }
  57585. if (this._renderEffect && this._renderEffect.defines === defines) {
  57586. return;
  57587. }
  57588. 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);
  57589. };
  57590. /**
  57591. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57592. * @param preWarm defines if we are in the pre-warmimg phase
  57593. */
  57594. GPUParticleSystem.prototype.animate = function (preWarm) {
  57595. if (preWarm === void 0) { preWarm = false; }
  57596. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57597. this._actualFrame += this._timeDelta;
  57598. if (!this._stopped) {
  57599. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57600. this.stop();
  57601. }
  57602. }
  57603. };
  57604. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57605. var texture = this[textureName];
  57606. if (!factorGradients || !factorGradients.length || texture) {
  57607. return;
  57608. }
  57609. var data = new Float32Array(this._rawTextureWidth);
  57610. for (var x = 0; x < this._rawTextureWidth; x++) {
  57611. var ratio = x / this._rawTextureWidth;
  57612. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57613. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57614. });
  57615. }
  57616. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57617. };
  57618. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57619. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57620. };
  57621. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57622. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57623. };
  57624. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  57625. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  57626. };
  57627. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57628. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57629. return;
  57630. }
  57631. var data = new Uint8Array(this._rawTextureWidth * 4);
  57632. var tmpColor = BABYLON.Tmp.Color4[0];
  57633. for (var x = 0; x < this._rawTextureWidth; x++) {
  57634. var ratio = x / this._rawTextureWidth;
  57635. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57636. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57637. data[x * 4] = tmpColor.r * 255;
  57638. data[x * 4 + 1] = tmpColor.g * 255;
  57639. data[x * 4 + 2] = tmpColor.b * 255;
  57640. data[x * 4 + 3] = tmpColor.a * 255;
  57641. });
  57642. }
  57643. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57644. };
  57645. /**
  57646. * Renders the particle system in its current state
  57647. * @param preWarm defines if the system should only update the particles but not render them
  57648. * @returns the current number of particles
  57649. */
  57650. GPUParticleSystem.prototype.render = function (preWarm) {
  57651. if (preWarm === void 0) { preWarm = false; }
  57652. if (!this._started) {
  57653. return 0;
  57654. }
  57655. this._createColorGradientTexture();
  57656. this._createSizeGradientTexture();
  57657. this._createAngularSpeedGradientTexture();
  57658. this._createVelocityGradientTexture();
  57659. this._recreateUpdateEffect();
  57660. this._recreateRenderEffect();
  57661. if (!this.isReady()) {
  57662. return 0;
  57663. }
  57664. if (!preWarm) {
  57665. if (!this._preWarmDone && this.preWarmCycles) {
  57666. for (var index = 0; index < this.preWarmCycles; index++) {
  57667. this.animate(true);
  57668. this.render(true);
  57669. }
  57670. this._preWarmDone = true;
  57671. }
  57672. if (this._currentRenderId === this._scene.getRenderId()) {
  57673. return 0;
  57674. }
  57675. this._currentRenderId = this._scene.getRenderId();
  57676. }
  57677. // Get everything ready to render
  57678. this._initialize();
  57679. this._accumulatedCount += this.emitRate * this._timeDelta;
  57680. if (this._accumulatedCount > 1) {
  57681. var intPart = this._accumulatedCount | 0;
  57682. this._accumulatedCount -= intPart;
  57683. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57684. }
  57685. if (!this._currentActiveCount) {
  57686. return 0;
  57687. }
  57688. // Enable update effect
  57689. this._engine.enableEffect(this._updateEffect);
  57690. this._engine.setState(false);
  57691. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57692. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57693. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57694. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57695. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57696. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57697. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57698. if (!this._colorGradientsTexture) {
  57699. this._updateEffect.setDirectColor4("color1", this.color1);
  57700. this._updateEffect.setDirectColor4("color2", this.color2);
  57701. }
  57702. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57703. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57704. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57705. this._updateEffect.setVector3("gravity", this.gravity);
  57706. if (this._sizeGradientsTexture) {
  57707. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57708. }
  57709. if (this._angularSpeedGradientsTexture) {
  57710. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  57711. }
  57712. if (this._velocityGradientsTexture) {
  57713. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  57714. }
  57715. if (this.particleEmitterType) {
  57716. this.particleEmitterType.applyToShader(this._updateEffect);
  57717. }
  57718. if (this._isAnimationSheetEnabled) {
  57719. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57720. }
  57721. var emitterWM;
  57722. if (this.emitter.position) {
  57723. var emitterMesh = this.emitter;
  57724. emitterWM = emitterMesh.getWorldMatrix();
  57725. }
  57726. else {
  57727. var emitterPosition = this.emitter;
  57728. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57729. }
  57730. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57731. // Bind source VAO
  57732. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57733. // Update
  57734. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57735. this._engine.setRasterizerState(false);
  57736. this._engine.beginTransformFeedback();
  57737. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57738. this._engine.endTransformFeedback();
  57739. this._engine.setRasterizerState(true);
  57740. this._engine.bindTransformFeedbackBuffer(null);
  57741. if (!preWarm) {
  57742. // Enable render effect
  57743. this._engine.enableEffect(this._renderEffect);
  57744. var viewMatrix = this._scene.getViewMatrix();
  57745. this._renderEffect.setMatrix("view", viewMatrix);
  57746. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57747. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57748. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57749. if (this._colorGradientsTexture) {
  57750. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57751. }
  57752. else {
  57753. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57754. }
  57755. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57756. var baseSize = this.particleTexture.getBaseSize();
  57757. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57758. }
  57759. if (this._isBillboardBased) {
  57760. var camera = this._scene.activeCamera;
  57761. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57762. }
  57763. if (this._scene.clipPlane) {
  57764. var clipPlane = this._scene.clipPlane;
  57765. var invView = viewMatrix.clone();
  57766. invView.invert();
  57767. this._renderEffect.setMatrix("invView", invView);
  57768. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57769. }
  57770. // Draw order
  57771. switch (this.blendMode) {
  57772. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57773. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57774. break;
  57775. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57776. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57777. break;
  57778. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57779. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57780. break;
  57781. }
  57782. if (this.forceDepthWrite) {
  57783. this._engine.setDepthWrite(true);
  57784. }
  57785. // Bind source VAO
  57786. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57787. // Render
  57788. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57789. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57790. }
  57791. // Switch VAOs
  57792. this._targetIndex++;
  57793. if (this._targetIndex === 2) {
  57794. this._targetIndex = 0;
  57795. }
  57796. // Switch buffers
  57797. var tmpBuffer = this._sourceBuffer;
  57798. this._sourceBuffer = this._targetBuffer;
  57799. this._targetBuffer = tmpBuffer;
  57800. return this._currentActiveCount;
  57801. };
  57802. /**
  57803. * Rebuilds the particle system
  57804. */
  57805. GPUParticleSystem.prototype.rebuild = function () {
  57806. this._initialize(true);
  57807. };
  57808. GPUParticleSystem.prototype._releaseBuffers = function () {
  57809. if (this._buffer0) {
  57810. this._buffer0.dispose();
  57811. this._buffer0 = null;
  57812. }
  57813. if (this._buffer1) {
  57814. this._buffer1.dispose();
  57815. this._buffer1 = null;
  57816. }
  57817. if (this._spriteBuffer) {
  57818. this._spriteBuffer.dispose();
  57819. this._spriteBuffer = null;
  57820. }
  57821. };
  57822. GPUParticleSystem.prototype._releaseVAOs = function () {
  57823. if (!this._updateVAO) {
  57824. return;
  57825. }
  57826. for (var index = 0; index < this._updateVAO.length; index++) {
  57827. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57828. }
  57829. this._updateVAO = [];
  57830. for (var index = 0; index < this._renderVAO.length; index++) {
  57831. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57832. }
  57833. this._renderVAO = [];
  57834. };
  57835. /**
  57836. * Disposes the particle system and free the associated resources
  57837. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57838. */
  57839. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57840. if (disposeTexture === void 0) { disposeTexture = true; }
  57841. var index = this._scene.particleSystems.indexOf(this);
  57842. if (index > -1) {
  57843. this._scene.particleSystems.splice(index, 1);
  57844. }
  57845. this._releaseBuffers();
  57846. this._releaseVAOs();
  57847. if (this._colorGradientsTexture) {
  57848. this._colorGradientsTexture.dispose();
  57849. this._colorGradientsTexture = null;
  57850. }
  57851. if (this._sizeGradientsTexture) {
  57852. this._sizeGradientsTexture.dispose();
  57853. this._sizeGradientsTexture = null;
  57854. }
  57855. if (this._angularSpeedGradientsTexture) {
  57856. this._angularSpeedGradientsTexture.dispose();
  57857. this._angularSpeedGradientsTexture = null;
  57858. }
  57859. if (this._velocityGradientsTexture) {
  57860. this._velocityGradientsTexture.dispose();
  57861. this._velocityGradientsTexture = null;
  57862. }
  57863. if (this._randomTexture) {
  57864. this._randomTexture.dispose();
  57865. this._randomTexture = null;
  57866. }
  57867. if (this._randomTexture2) {
  57868. this._randomTexture2.dispose();
  57869. this._randomTexture2 = null;
  57870. }
  57871. if (disposeTexture && this.particleTexture) {
  57872. this.particleTexture.dispose();
  57873. this.particleTexture = null;
  57874. }
  57875. // Callback
  57876. this.onDisposeObservable.notifyObservers(this);
  57877. this.onDisposeObservable.clear();
  57878. };
  57879. /**
  57880. * Clones the particle system.
  57881. * @param name The name of the cloned object
  57882. * @param newEmitter The new emitter to use
  57883. * @returns the cloned particle system
  57884. */
  57885. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57886. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57887. BABYLON.Tools.DeepCopy(this, result);
  57888. if (newEmitter === undefined) {
  57889. newEmitter = this.emitter;
  57890. }
  57891. result.emitter = newEmitter;
  57892. if (this.particleTexture) {
  57893. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57894. }
  57895. return result;
  57896. };
  57897. /**
  57898. * Serializes the particle system to a JSON object.
  57899. * @returns the JSON object
  57900. */
  57901. GPUParticleSystem.prototype.serialize = function () {
  57902. var serializationObject = {};
  57903. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57904. serializationObject.activeParticleCount = this.activeParticleCount;
  57905. return serializationObject;
  57906. };
  57907. /**
  57908. * Parses a JSON object to create a GPU particle system.
  57909. * @param parsedParticleSystem The JSON object to parse
  57910. * @param scene The scene to create the particle system in
  57911. * @param rootUrl The root url to use to load external dependencies like texture
  57912. * @returns the parsed GPU particle system
  57913. */
  57914. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57915. var name = parsedParticleSystem.name;
  57916. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57917. if (parsedParticleSystem.activeParticleCount) {
  57918. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57919. }
  57920. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57921. return particleSystem;
  57922. };
  57923. return GPUParticleSystem;
  57924. }());
  57925. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57926. })(BABYLON || (BABYLON = {}));
  57927. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57928. var BABYLON;
  57929. (function (BABYLON) {
  57930. /**
  57931. * Represents one particle of a solid particle system.
  57932. */
  57933. var SolidParticle = /** @class */ (function () {
  57934. /**
  57935. * Creates a Solid Particle object.
  57936. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57937. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57938. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57939. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57940. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57941. * @param shapeId (integer) is the model shape identifier in the SPS.
  57942. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57943. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57944. */
  57945. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57946. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57947. /**
  57948. * particle global index
  57949. */
  57950. this.idx = 0;
  57951. /**
  57952. * The color of the particle
  57953. */
  57954. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57955. /**
  57956. * The world space position of the particle.
  57957. */
  57958. this.position = BABYLON.Vector3.Zero();
  57959. /**
  57960. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57961. */
  57962. this.rotation = BABYLON.Vector3.Zero();
  57963. /**
  57964. * The scaling of the particle.
  57965. */
  57966. this.scaling = BABYLON.Vector3.One();
  57967. /**
  57968. * The uvs of the particle.
  57969. */
  57970. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57971. /**
  57972. * The current speed of the particle.
  57973. */
  57974. this.velocity = BABYLON.Vector3.Zero();
  57975. /**
  57976. * The pivot point in the particle local space.
  57977. */
  57978. this.pivot = BABYLON.Vector3.Zero();
  57979. /**
  57980. * Must the particle be translated from its pivot point in its local space ?
  57981. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57982. * Default : false
  57983. */
  57984. this.translateFromPivot = false;
  57985. /**
  57986. * Is the particle active or not ?
  57987. */
  57988. this.alive = true;
  57989. /**
  57990. * Is the particle visible or not ?
  57991. */
  57992. this.isVisible = true;
  57993. /**
  57994. * Index of this particle in the global "positions" array (Internal use)
  57995. */
  57996. this._pos = 0;
  57997. /**
  57998. * Index of this particle in the global "indices" array (Internal use)
  57999. */
  58000. this._ind = 0;
  58001. /**
  58002. * ModelShape id of this particle
  58003. */
  58004. this.shapeId = 0;
  58005. /**
  58006. * Index of the particle in its shape id (Internal use)
  58007. */
  58008. this.idxInShape = 0;
  58009. /**
  58010. * Still set as invisible in order to skip useless computations (Internal use)
  58011. */
  58012. this._stillInvisible = false;
  58013. /**
  58014. * Last computed particle rotation matrix
  58015. */
  58016. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58017. /**
  58018. * Parent particle Id, if any.
  58019. * Default null.
  58020. */
  58021. this.parentId = null;
  58022. /**
  58023. * Internal global position in the SPS.
  58024. */
  58025. this._globalPosition = BABYLON.Vector3.Zero();
  58026. this.idx = particleIndex;
  58027. this._pos = positionIndex;
  58028. this._ind = indiceIndex;
  58029. this._model = model;
  58030. this.shapeId = shapeId;
  58031. this.idxInShape = idxInShape;
  58032. this._sps = sps;
  58033. if (modelBoundingInfo) {
  58034. this._modelBoundingInfo = modelBoundingInfo;
  58035. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58036. }
  58037. }
  58038. Object.defineProperty(SolidParticle.prototype, "scale", {
  58039. /**
  58040. * Legacy support, changed scale to scaling
  58041. */
  58042. get: function () {
  58043. return this.scaling;
  58044. },
  58045. /**
  58046. * Legacy support, changed scale to scaling
  58047. */
  58048. set: function (scale) {
  58049. this.scaling = scale;
  58050. },
  58051. enumerable: true,
  58052. configurable: true
  58053. });
  58054. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58055. /**
  58056. * Legacy support, changed quaternion to rotationQuaternion
  58057. */
  58058. get: function () {
  58059. return this.rotationQuaternion;
  58060. },
  58061. /**
  58062. * Legacy support, changed quaternion to rotationQuaternion
  58063. */
  58064. set: function (q) {
  58065. this.rotationQuaternion = q;
  58066. },
  58067. enumerable: true,
  58068. configurable: true
  58069. });
  58070. /**
  58071. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58072. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58073. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58074. * @returns true if it intersects
  58075. */
  58076. SolidParticle.prototype.intersectsMesh = function (target) {
  58077. if (!this._boundingInfo || !target._boundingInfo) {
  58078. return false;
  58079. }
  58080. if (this._sps._bSphereOnly) {
  58081. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58082. }
  58083. return this._boundingInfo.intersects(target._boundingInfo, false);
  58084. };
  58085. return SolidParticle;
  58086. }());
  58087. BABYLON.SolidParticle = SolidParticle;
  58088. /**
  58089. * Represents the shape of the model used by one particle of a solid particle system.
  58090. * SPS internal tool, don't use it manually.
  58091. */
  58092. var ModelShape = /** @class */ (function () {
  58093. /**
  58094. * 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.
  58095. * SPS internal tool, don't use it manually.
  58096. * @hidden
  58097. */
  58098. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58099. /**
  58100. * length of the shape in the model indices array (internal use)
  58101. */
  58102. this._indicesLength = 0;
  58103. this.shapeID = id;
  58104. this._shape = shape;
  58105. this._indicesLength = indicesLength;
  58106. this._shapeUV = shapeUV;
  58107. this._positionFunction = posFunction;
  58108. this._vertexFunction = vtxFunction;
  58109. }
  58110. return ModelShape;
  58111. }());
  58112. BABYLON.ModelShape = ModelShape;
  58113. /**
  58114. * Represents a Depth Sorted Particle in the solid particle system.
  58115. */
  58116. var DepthSortedParticle = /** @class */ (function () {
  58117. function DepthSortedParticle() {
  58118. /**
  58119. * Index of the particle in the "indices" array
  58120. */
  58121. this.ind = 0;
  58122. /**
  58123. * Length of the particle shape in the "indices" array
  58124. */
  58125. this.indicesLength = 0;
  58126. /**
  58127. * Squared distance from the particle to the camera
  58128. */
  58129. this.sqDistance = 0.0;
  58130. }
  58131. return DepthSortedParticle;
  58132. }());
  58133. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58134. })(BABYLON || (BABYLON = {}));
  58135. //# sourceMappingURL=babylon.solidParticle.js.map
  58136. var BABYLON;
  58137. (function (BABYLON) {
  58138. /**
  58139. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58140. *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.
  58141. * The SPS is also a particle system. It provides some methods to manage the particles.
  58142. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58143. *
  58144. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58145. */
  58146. var SolidParticleSystem = /** @class */ (function () {
  58147. /**
  58148. * Creates a SPS (Solid Particle System) object.
  58149. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58150. * @param scene (Scene) is the scene in which the SPS is added.
  58151. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58152. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58153. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58154. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58155. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58156. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58157. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58158. */
  58159. function SolidParticleSystem(name, scene, options) {
  58160. /**
  58161. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58162. * Example : var p = SPS.particles[i];
  58163. */
  58164. this.particles = new Array();
  58165. /**
  58166. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58167. */
  58168. this.nbParticles = 0;
  58169. /**
  58170. * If the particles must ever face the camera (default false). Useful for planar particles.
  58171. */
  58172. this.billboard = false;
  58173. /**
  58174. * Recompute normals when adding a shape
  58175. */
  58176. this.recomputeNormals = true;
  58177. /**
  58178. * This a counter ofr your own usage. It's not set by any SPS functions.
  58179. */
  58180. this.counter = 0;
  58181. /**
  58182. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58183. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58184. */
  58185. this.vars = {};
  58186. /**
  58187. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58188. */
  58189. this._bSphereOnly = false;
  58190. /**
  58191. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58192. */
  58193. this._bSphereRadiusFactor = 1.0;
  58194. this._positions = new Array();
  58195. this._indices = new Array();
  58196. this._normals = new Array();
  58197. this._colors = new Array();
  58198. this._uvs = new Array();
  58199. this._index = 0; // indices index
  58200. this._updatable = true;
  58201. this._pickable = false;
  58202. this._isVisibilityBoxLocked = false;
  58203. this._alwaysVisible = false;
  58204. this._depthSort = false;
  58205. this._shapeCounter = 0;
  58206. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58207. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58208. this._computeParticleColor = true;
  58209. this._computeParticleTexture = true;
  58210. this._computeParticleRotation = true;
  58211. this._computeParticleVertex = false;
  58212. this._computeBoundingBox = false;
  58213. this._depthSortParticles = true;
  58214. this._cam_axisZ = BABYLON.Vector3.Zero();
  58215. this._cam_axisY = BABYLON.Vector3.Zero();
  58216. this._cam_axisX = BABYLON.Vector3.Zero();
  58217. this._axisZ = BABYLON.Axis.Z;
  58218. this._camDir = BABYLON.Vector3.Zero();
  58219. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58220. this._rotMatrix = new BABYLON.Matrix();
  58221. this._invertMatrix = new BABYLON.Matrix();
  58222. this._rotated = BABYLON.Vector3.Zero();
  58223. this._quaternion = new BABYLON.Quaternion();
  58224. this._vertex = BABYLON.Vector3.Zero();
  58225. this._normal = BABYLON.Vector3.Zero();
  58226. this._yaw = 0.0;
  58227. this._pitch = 0.0;
  58228. this._roll = 0.0;
  58229. this._halfroll = 0.0;
  58230. this._halfpitch = 0.0;
  58231. this._halfyaw = 0.0;
  58232. this._sinRoll = 0.0;
  58233. this._cosRoll = 0.0;
  58234. this._sinPitch = 0.0;
  58235. this._cosPitch = 0.0;
  58236. this._sinYaw = 0.0;
  58237. this._cosYaw = 0.0;
  58238. this._mustUnrotateFixedNormals = false;
  58239. this._minimum = BABYLON.Vector3.Zero();
  58240. this._maximum = BABYLON.Vector3.Zero();
  58241. this._minBbox = BABYLON.Vector3.Zero();
  58242. this._maxBbox = BABYLON.Vector3.Zero();
  58243. this._particlesIntersect = false;
  58244. this._depthSortFunction = function (p1, p2) {
  58245. return (p2.sqDistance - p1.sqDistance);
  58246. };
  58247. this._needs32Bits = false;
  58248. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58249. this._scaledPivot = BABYLON.Vector3.Zero();
  58250. this._particleHasParent = false;
  58251. this.name = name;
  58252. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58253. this._camera = scene.activeCamera;
  58254. this._pickable = options ? options.isPickable : false;
  58255. this._depthSort = options ? options.enableDepthSort : false;
  58256. this._particlesIntersect = options ? options.particleIntersection : false;
  58257. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58258. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58259. if (options && options.updatable !== undefined) {
  58260. this._updatable = options.updatable;
  58261. }
  58262. else {
  58263. this._updatable = true;
  58264. }
  58265. if (this._pickable) {
  58266. this.pickedParticles = [];
  58267. }
  58268. if (this._depthSort) {
  58269. this.depthSortedParticles = [];
  58270. }
  58271. }
  58272. /**
  58273. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58274. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58275. * @returns the created mesh
  58276. */
  58277. SolidParticleSystem.prototype.buildMesh = function () {
  58278. if (this.nbParticles === 0) {
  58279. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58280. this.addShape(triangle, 1);
  58281. triangle.dispose();
  58282. }
  58283. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58284. this._positions32 = new Float32Array(this._positions);
  58285. this._uvs32 = new Float32Array(this._uvs);
  58286. this._colors32 = new Float32Array(this._colors);
  58287. if (this.recomputeNormals) {
  58288. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58289. }
  58290. this._normals32 = new Float32Array(this._normals);
  58291. this._fixedNormal32 = new Float32Array(this._normals);
  58292. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58293. this._unrotateFixedNormals();
  58294. }
  58295. var vertexData = new BABYLON.VertexData();
  58296. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58297. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58298. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58299. if (this._uvs32.length > 0) {
  58300. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58301. }
  58302. if (this._colors32.length > 0) {
  58303. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58304. }
  58305. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58306. vertexData.applyToMesh(mesh, this._updatable);
  58307. this.mesh = mesh;
  58308. this.mesh.isPickable = this._pickable;
  58309. // free memory
  58310. if (!this._depthSort) {
  58311. this._indices = null;
  58312. }
  58313. this._positions = null;
  58314. this._normals = null;
  58315. this._uvs = null;
  58316. this._colors = null;
  58317. if (!this._updatable) {
  58318. this.particles.length = 0;
  58319. }
  58320. return mesh;
  58321. };
  58322. /**
  58323. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58324. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58325. * Thus the particles generated from `digest()` have their property `position` set yet.
  58326. * @param mesh ( Mesh ) is the mesh to be digested
  58327. * @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
  58328. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58329. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58330. * @returns the current SPS
  58331. */
  58332. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58333. var size = (options && options.facetNb) || 1;
  58334. var number = (options && options.number) || 0;
  58335. var delta = (options && options.delta) || 0;
  58336. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58337. var meshInd = mesh.getIndices();
  58338. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58339. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58340. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58341. var f = 0; // facet counter
  58342. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58343. // compute size from number
  58344. if (number) {
  58345. number = (number > totalFacets) ? totalFacets : number;
  58346. size = Math.round(totalFacets / number);
  58347. delta = 0;
  58348. }
  58349. else {
  58350. size = (size > totalFacets) ? totalFacets : size;
  58351. }
  58352. var facetPos = []; // submesh positions
  58353. var facetInd = []; // submesh indices
  58354. var facetUV = []; // submesh UV
  58355. var facetCol = []; // submesh colors
  58356. var barycenter = BABYLON.Vector3.Zero();
  58357. var sizeO = size;
  58358. while (f < totalFacets) {
  58359. size = sizeO + Math.floor((1 + delta) * Math.random());
  58360. if (f > totalFacets - size) {
  58361. size = totalFacets - f;
  58362. }
  58363. // reset temp arrays
  58364. facetPos.length = 0;
  58365. facetInd.length = 0;
  58366. facetUV.length = 0;
  58367. facetCol.length = 0;
  58368. // iterate over "size" facets
  58369. var fi = 0;
  58370. for (var j = f * 3; j < (f + size) * 3; j++) {
  58371. facetInd.push(fi);
  58372. var i = meshInd[j];
  58373. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58374. if (meshUV) {
  58375. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58376. }
  58377. if (meshCol) {
  58378. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58379. }
  58380. fi++;
  58381. }
  58382. // create a model shape for each single particle
  58383. var idx = this.nbParticles;
  58384. var shape = this._posToShape(facetPos);
  58385. var shapeUV = this._uvsToShapeUV(facetUV);
  58386. // compute the barycenter of the shape
  58387. var v;
  58388. for (v = 0; v < shape.length; v++) {
  58389. barycenter.addInPlace(shape[v]);
  58390. }
  58391. barycenter.scaleInPlace(1 / shape.length);
  58392. // shift the shape from its barycenter to the origin
  58393. for (v = 0; v < shape.length; v++) {
  58394. shape[v].subtractInPlace(barycenter);
  58395. }
  58396. var bInfo;
  58397. if (this._particlesIntersect) {
  58398. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58399. }
  58400. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58401. // add the particle in the SPS
  58402. var currentPos = this._positions.length;
  58403. var currentInd = this._indices.length;
  58404. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58405. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58406. // initialize the particle position
  58407. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58408. this._index += shape.length;
  58409. idx++;
  58410. this.nbParticles++;
  58411. this._shapeCounter++;
  58412. f += size;
  58413. }
  58414. return this;
  58415. };
  58416. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58417. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58418. var index = 0;
  58419. var idx = 0;
  58420. for (var p = 0; p < this.particles.length; p++) {
  58421. this._particle = this.particles[p];
  58422. this._shape = this._particle._model._shape;
  58423. if (this._particle.rotationQuaternion) {
  58424. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58425. }
  58426. else {
  58427. this._yaw = this._particle.rotation.y;
  58428. this._pitch = this._particle.rotation.x;
  58429. this._roll = this._particle.rotation.z;
  58430. this._quaternionRotationYPR();
  58431. }
  58432. this._quaternionToRotationMatrix();
  58433. this._rotMatrix.invertToRef(this._invertMatrix);
  58434. for (var pt = 0; pt < this._shape.length; pt++) {
  58435. idx = index + pt * 3;
  58436. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58437. this._fixedNormal32[idx] = this._normal.x;
  58438. this._fixedNormal32[idx + 1] = this._normal.y;
  58439. this._fixedNormal32[idx + 2] = this._normal.z;
  58440. }
  58441. index = idx + 3;
  58442. }
  58443. };
  58444. //reset copy
  58445. SolidParticleSystem.prototype._resetCopy = function () {
  58446. this._copy.position.x = 0;
  58447. this._copy.position.y = 0;
  58448. this._copy.position.z = 0;
  58449. this._copy.rotation.x = 0;
  58450. this._copy.rotation.y = 0;
  58451. this._copy.rotation.z = 0;
  58452. this._copy.rotationQuaternion = null;
  58453. this._copy.scaling.x = 1.0;
  58454. this._copy.scaling.y = 1.0;
  58455. this._copy.scaling.z = 1.0;
  58456. this._copy.uvs.x = 0;
  58457. this._copy.uvs.y = 0;
  58458. this._copy.uvs.z = 1.0;
  58459. this._copy.uvs.w = 1.0;
  58460. this._copy.color = null;
  58461. this._copy.translateFromPivot = false;
  58462. };
  58463. // _meshBuilder : inserts the shape model in the global SPS mesh
  58464. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58465. var i;
  58466. var u = 0;
  58467. var c = 0;
  58468. var n = 0;
  58469. this._resetCopy();
  58470. if (options && options.positionFunction) { // call to custom positionFunction
  58471. options.positionFunction(this._copy, idx, idxInShape);
  58472. this._mustUnrotateFixedNormals = true;
  58473. }
  58474. if (this._copy.rotationQuaternion) {
  58475. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58476. }
  58477. else {
  58478. this._yaw = this._copy.rotation.y;
  58479. this._pitch = this._copy.rotation.x;
  58480. this._roll = this._copy.rotation.z;
  58481. this._quaternionRotationYPR();
  58482. }
  58483. this._quaternionToRotationMatrix();
  58484. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58485. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58486. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58487. if (this._copy.translateFromPivot) {
  58488. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58489. }
  58490. else {
  58491. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58492. }
  58493. for (i = 0; i < shape.length; i++) {
  58494. this._vertex.x = shape[i].x;
  58495. this._vertex.y = shape[i].y;
  58496. this._vertex.z = shape[i].z;
  58497. if (options && options.vertexFunction) {
  58498. options.vertexFunction(this._copy, this._vertex, i);
  58499. }
  58500. this._vertex.x *= this._copy.scaling.x;
  58501. this._vertex.y *= this._copy.scaling.y;
  58502. this._vertex.z *= this._copy.scaling.z;
  58503. this._vertex.x -= this._scaledPivot.x;
  58504. this._vertex.y -= this._scaledPivot.y;
  58505. this._vertex.z -= this._scaledPivot.z;
  58506. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58507. this._rotated.addInPlace(this._pivotBackTranslation);
  58508. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58509. if (meshUV) {
  58510. 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);
  58511. u += 2;
  58512. }
  58513. if (this._copy.color) {
  58514. this._color = this._copy.color;
  58515. }
  58516. else if (meshCol && meshCol[c] !== undefined) {
  58517. this._color.r = meshCol[c];
  58518. this._color.g = meshCol[c + 1];
  58519. this._color.b = meshCol[c + 2];
  58520. this._color.a = meshCol[c + 3];
  58521. }
  58522. else {
  58523. this._color.r = 1.0;
  58524. this._color.g = 1.0;
  58525. this._color.b = 1.0;
  58526. this._color.a = 1.0;
  58527. }
  58528. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58529. c += 4;
  58530. if (!this.recomputeNormals && meshNor) {
  58531. this._normal.x = meshNor[n];
  58532. this._normal.y = meshNor[n + 1];
  58533. this._normal.z = meshNor[n + 2];
  58534. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58535. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58536. n += 3;
  58537. }
  58538. }
  58539. for (i = 0; i < meshInd.length; i++) {
  58540. var current_ind = p + meshInd[i];
  58541. indices.push(current_ind);
  58542. if (current_ind > 65535) {
  58543. this._needs32Bits = true;
  58544. }
  58545. }
  58546. if (this._pickable) {
  58547. var nbfaces = meshInd.length / 3;
  58548. for (i = 0; i < nbfaces; i++) {
  58549. this.pickedParticles.push({ idx: idx, faceId: i });
  58550. }
  58551. }
  58552. if (this._depthSort) {
  58553. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58554. }
  58555. return this._copy;
  58556. };
  58557. // returns a shape array from positions array
  58558. SolidParticleSystem.prototype._posToShape = function (positions) {
  58559. var shape = [];
  58560. for (var i = 0; i < positions.length; i += 3) {
  58561. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58562. }
  58563. return shape;
  58564. };
  58565. // returns a shapeUV array from a Vector4 uvs
  58566. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58567. var shapeUV = [];
  58568. if (uvs) {
  58569. for (var i = 0; i < uvs.length; i++)
  58570. shapeUV.push(uvs[i]);
  58571. }
  58572. return shapeUV;
  58573. };
  58574. // adds a new particle object in the particles array
  58575. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58576. if (bInfo === void 0) { bInfo = null; }
  58577. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58578. this.particles.push(sp);
  58579. return sp;
  58580. };
  58581. /**
  58582. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58583. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58584. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58585. * @param nb (positive integer) the number of particles to be created from this model
  58586. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58587. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58588. * @returns the number of shapes in the system
  58589. */
  58590. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58591. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58592. var meshInd = mesh.getIndices();
  58593. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58594. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58595. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58596. var bbInfo;
  58597. if (this._particlesIntersect) {
  58598. bbInfo = mesh.getBoundingInfo();
  58599. }
  58600. var shape = this._posToShape(meshPos);
  58601. var shapeUV = this._uvsToShapeUV(meshUV);
  58602. var posfunc = options ? options.positionFunction : null;
  58603. var vtxfunc = options ? options.vertexFunction : null;
  58604. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58605. // particles
  58606. var sp;
  58607. var currentCopy;
  58608. var idx = this.nbParticles;
  58609. for (var i = 0; i < nb; i++) {
  58610. var currentPos = this._positions.length;
  58611. var currentInd = this._indices.length;
  58612. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58613. if (this._updatable) {
  58614. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58615. sp.position.copyFrom(currentCopy.position);
  58616. sp.rotation.copyFrom(currentCopy.rotation);
  58617. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58618. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58619. }
  58620. if (currentCopy.color && sp.color) {
  58621. sp.color.copyFrom(currentCopy.color);
  58622. }
  58623. sp.scaling.copyFrom(currentCopy.scaling);
  58624. sp.uvs.copyFrom(currentCopy.uvs);
  58625. }
  58626. this._index += shape.length;
  58627. idx++;
  58628. }
  58629. this.nbParticles += nb;
  58630. this._shapeCounter++;
  58631. return this._shapeCounter - 1;
  58632. };
  58633. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58634. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58635. this._resetCopy();
  58636. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58637. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58638. }
  58639. if (this._copy.rotationQuaternion) {
  58640. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58641. }
  58642. else {
  58643. this._yaw = this._copy.rotation.y;
  58644. this._pitch = this._copy.rotation.x;
  58645. this._roll = this._copy.rotation.z;
  58646. this._quaternionRotationYPR();
  58647. }
  58648. this._quaternionToRotationMatrix();
  58649. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58650. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58651. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58652. if (this._copy.translateFromPivot) {
  58653. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58654. }
  58655. else {
  58656. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58657. }
  58658. this._shape = particle._model._shape;
  58659. for (var pt = 0; pt < this._shape.length; pt++) {
  58660. this._vertex.x = this._shape[pt].x;
  58661. this._vertex.y = this._shape[pt].y;
  58662. this._vertex.z = this._shape[pt].z;
  58663. if (particle._model._vertexFunction) {
  58664. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58665. }
  58666. this._vertex.x *= this._copy.scaling.x;
  58667. this._vertex.y *= this._copy.scaling.y;
  58668. this._vertex.z *= this._copy.scaling.z;
  58669. this._vertex.x -= this._scaledPivot.x;
  58670. this._vertex.y -= this._scaledPivot.y;
  58671. this._vertex.z -= this._scaledPivot.z;
  58672. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58673. this._rotated.addInPlace(this._pivotBackTranslation);
  58674. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58675. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58676. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58677. }
  58678. particle.position.x = 0.0;
  58679. particle.position.y = 0.0;
  58680. particle.position.z = 0.0;
  58681. particle.rotation.x = 0.0;
  58682. particle.rotation.y = 0.0;
  58683. particle.rotation.z = 0.0;
  58684. particle.rotationQuaternion = null;
  58685. particle.scaling.x = 1.0;
  58686. particle.scaling.y = 1.0;
  58687. particle.scaling.z = 1.0;
  58688. particle.uvs.x = 0.0;
  58689. particle.uvs.y = 0.0;
  58690. particle.uvs.z = 1.0;
  58691. particle.uvs.w = 1.0;
  58692. particle.pivot.x = 0.0;
  58693. particle.pivot.y = 0.0;
  58694. particle.pivot.z = 0.0;
  58695. particle.translateFromPivot = false;
  58696. particle.parentId = null;
  58697. };
  58698. /**
  58699. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58700. * @returns the SPS.
  58701. */
  58702. SolidParticleSystem.prototype.rebuildMesh = function () {
  58703. for (var p = 0; p < this.particles.length; p++) {
  58704. this._rebuildParticle(this.particles[p]);
  58705. }
  58706. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58707. return this;
  58708. };
  58709. /**
  58710. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58711. * This method calls `updateParticle()` for each particle of the SPS.
  58712. * For an animated SPS, it is usually called within the render loop.
  58713. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58714. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58715. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58716. * @returns the SPS.
  58717. */
  58718. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58719. if (start === void 0) { start = 0; }
  58720. if (end === void 0) { end = this.nbParticles - 1; }
  58721. if (update === void 0) { update = true; }
  58722. if (!this._updatable) {
  58723. return this;
  58724. }
  58725. // custom beforeUpdate
  58726. this.beforeUpdateParticles(start, end, update);
  58727. this._cam_axisX.x = 1.0;
  58728. this._cam_axisX.y = 0.0;
  58729. this._cam_axisX.z = 0.0;
  58730. this._cam_axisY.x = 0.0;
  58731. this._cam_axisY.y = 1.0;
  58732. this._cam_axisY.z = 0.0;
  58733. this._cam_axisZ.x = 0.0;
  58734. this._cam_axisZ.y = 0.0;
  58735. this._cam_axisZ.z = 1.0;
  58736. // cases when the World Matrix is to be computed first
  58737. if (this.billboard || this._depthSort) {
  58738. this.mesh.computeWorldMatrix(true);
  58739. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58740. }
  58741. // if the particles will always face the camera
  58742. if (this.billboard) {
  58743. // compute the camera position and un-rotate it by the current mesh rotation
  58744. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58745. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58746. this._cam_axisZ.normalize();
  58747. // same for camera up vector extracted from the cam view matrix
  58748. var view = this._camera.getViewMatrix(true);
  58749. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58750. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58751. this._cam_axisY.normalize();
  58752. this._cam_axisX.normalize();
  58753. }
  58754. // if depthSort, compute the camera global position in the mesh local system
  58755. if (this._depthSort) {
  58756. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58757. }
  58758. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58759. var idx = 0; // current position index in the global array positions32
  58760. var index = 0; // position start index in the global array positions32 of the current particle
  58761. var colidx = 0; // current color index in the global array colors32
  58762. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58763. var uvidx = 0; // current uv index in the global array uvs32
  58764. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58765. var pt = 0; // current index in the particle model shape
  58766. if (this.mesh.isFacetDataEnabled) {
  58767. this._computeBoundingBox = true;
  58768. }
  58769. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58770. if (this._computeBoundingBox) {
  58771. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58772. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58773. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58774. }
  58775. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58776. if (this.mesh._boundingInfo) {
  58777. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58778. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58779. }
  58780. }
  58781. }
  58782. // particle loop
  58783. index = this.particles[start]._pos;
  58784. var vpos = (index / 3) | 0;
  58785. colorIndex = vpos * 4;
  58786. uvIndex = vpos * 2;
  58787. for (var p = start; p <= end; p++) {
  58788. this._particle = this.particles[p];
  58789. this._shape = this._particle._model._shape;
  58790. this._shapeUV = this._particle._model._shapeUV;
  58791. // call to custom user function to update the particle properties
  58792. this.updateParticle(this._particle);
  58793. // camera-particle distance for depth sorting
  58794. if (this._depthSort && this._depthSortParticles) {
  58795. var dsp = this.depthSortedParticles[p];
  58796. dsp.ind = this._particle._ind;
  58797. dsp.indicesLength = this._particle._model._indicesLength;
  58798. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58799. }
  58800. // skip the computations for inactive or already invisible particles
  58801. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58802. // increment indexes for the next particle
  58803. pt = this._shape.length;
  58804. index += pt * 3;
  58805. colorIndex += pt * 4;
  58806. uvIndex += pt * 2;
  58807. continue;
  58808. }
  58809. if (this._particle.isVisible) {
  58810. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58811. this._particleHasParent = (this._particle.parentId !== null);
  58812. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58813. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58814. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58815. // particle rotation matrix
  58816. if (this.billboard) {
  58817. this._particle.rotation.x = 0.0;
  58818. this._particle.rotation.y = 0.0;
  58819. }
  58820. if (this._computeParticleRotation || this.billboard) {
  58821. if (this._particle.rotationQuaternion) {
  58822. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58823. }
  58824. else {
  58825. this._yaw = this._particle.rotation.y;
  58826. this._pitch = this._particle.rotation.x;
  58827. this._roll = this._particle.rotation.z;
  58828. this._quaternionRotationYPR();
  58829. }
  58830. this._quaternionToRotationMatrix();
  58831. }
  58832. if (this._particleHasParent) {
  58833. this._parent = this.particles[this._particle.parentId];
  58834. 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];
  58835. 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];
  58836. 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];
  58837. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58838. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58839. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58840. if (this._computeParticleRotation || this.billboard) {
  58841. 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];
  58842. 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];
  58843. 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];
  58844. 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];
  58845. 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];
  58846. 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];
  58847. 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];
  58848. 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];
  58849. 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];
  58850. }
  58851. }
  58852. else {
  58853. this._particle._globalPosition.x = this._particle.position.x;
  58854. this._particle._globalPosition.y = this._particle.position.y;
  58855. this._particle._globalPosition.z = this._particle.position.z;
  58856. if (this._computeParticleRotation || this.billboard) {
  58857. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58858. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58859. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58860. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58861. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58862. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58863. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58864. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58865. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58866. }
  58867. }
  58868. if (this._particle.translateFromPivot) {
  58869. this._pivotBackTranslation.x = 0.0;
  58870. this._pivotBackTranslation.y = 0.0;
  58871. this._pivotBackTranslation.z = 0.0;
  58872. }
  58873. else {
  58874. this._pivotBackTranslation.x = this._scaledPivot.x;
  58875. this._pivotBackTranslation.y = this._scaledPivot.y;
  58876. this._pivotBackTranslation.z = this._scaledPivot.z;
  58877. }
  58878. // particle vertex loop
  58879. for (pt = 0; pt < this._shape.length; pt++) {
  58880. idx = index + pt * 3;
  58881. colidx = colorIndex + pt * 4;
  58882. uvidx = uvIndex + pt * 2;
  58883. this._vertex.x = this._shape[pt].x;
  58884. this._vertex.y = this._shape[pt].y;
  58885. this._vertex.z = this._shape[pt].z;
  58886. if (this._computeParticleVertex) {
  58887. this.updateParticleVertex(this._particle, this._vertex, pt);
  58888. }
  58889. // positions
  58890. this._vertex.x *= this._particle.scaling.x;
  58891. this._vertex.y *= this._particle.scaling.y;
  58892. this._vertex.z *= this._particle.scaling.z;
  58893. this._vertex.x -= this._scaledPivot.x;
  58894. this._vertex.y -= this._scaledPivot.y;
  58895. this._vertex.z -= this._scaledPivot.z;
  58896. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58897. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58898. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58899. this._rotated.x += this._pivotBackTranslation.x;
  58900. this._rotated.y += this._pivotBackTranslation.y;
  58901. this._rotated.z += this._pivotBackTranslation.z;
  58902. 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;
  58903. 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;
  58904. 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;
  58905. if (this._computeBoundingBox) {
  58906. if (this._positions32[idx] < this._minimum.x) {
  58907. this._minimum.x = this._positions32[idx];
  58908. }
  58909. if (this._positions32[idx] > this._maximum.x) {
  58910. this._maximum.x = this._positions32[idx];
  58911. }
  58912. if (this._positions32[idx + 1] < this._minimum.y) {
  58913. this._minimum.y = this._positions32[idx + 1];
  58914. }
  58915. if (this._positions32[idx + 1] > this._maximum.y) {
  58916. this._maximum.y = this._positions32[idx + 1];
  58917. }
  58918. if (this._positions32[idx + 2] < this._minimum.z) {
  58919. this._minimum.z = this._positions32[idx + 2];
  58920. }
  58921. if (this._positions32[idx + 2] > this._maximum.z) {
  58922. this._maximum.z = this._positions32[idx + 2];
  58923. }
  58924. }
  58925. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58926. if (!this._computeParticleVertex) {
  58927. this._normal.x = this._fixedNormal32[idx];
  58928. this._normal.y = this._fixedNormal32[idx + 1];
  58929. this._normal.z = this._fixedNormal32[idx + 2];
  58930. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58931. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58932. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58933. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58934. 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;
  58935. 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;
  58936. }
  58937. if (this._computeParticleColor && this._particle.color) {
  58938. this._colors32[colidx] = this._particle.color.r;
  58939. this._colors32[colidx + 1] = this._particle.color.g;
  58940. this._colors32[colidx + 2] = this._particle.color.b;
  58941. this._colors32[colidx + 3] = this._particle.color.a;
  58942. }
  58943. if (this._computeParticleTexture) {
  58944. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58945. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58946. }
  58947. }
  58948. }
  58949. // particle just set invisible : scaled to zero and positioned at the origin
  58950. else {
  58951. this._particle._stillInvisible = true; // mark the particle as invisible
  58952. for (pt = 0; pt < this._shape.length; pt++) {
  58953. idx = index + pt * 3;
  58954. colidx = colorIndex + pt * 4;
  58955. uvidx = uvIndex + pt * 2;
  58956. this._positions32[idx] = 0.0;
  58957. this._positions32[idx + 1] = 0.0;
  58958. this._positions32[idx + 2] = 0.0;
  58959. this._normals32[idx] = 0.0;
  58960. this._normals32[idx + 1] = 0.0;
  58961. this._normals32[idx + 2] = 0.0;
  58962. if (this._computeParticleColor && this._particle.color) {
  58963. this._colors32[colidx] = this._particle.color.r;
  58964. this._colors32[colidx + 1] = this._particle.color.g;
  58965. this._colors32[colidx + 2] = this._particle.color.b;
  58966. this._colors32[colidx + 3] = this._particle.color.a;
  58967. }
  58968. if (this._computeParticleTexture) {
  58969. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58970. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58971. }
  58972. }
  58973. }
  58974. // if the particle intersections must be computed : update the bbInfo
  58975. if (this._particlesIntersect) {
  58976. var bInfo = this._particle._boundingInfo;
  58977. var bBox = bInfo.boundingBox;
  58978. var bSphere = bInfo.boundingSphere;
  58979. if (!this._bSphereOnly) {
  58980. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58981. for (var b = 0; b < bBox.vectors.length; b++) {
  58982. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58983. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58984. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58985. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58986. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58987. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58988. 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;
  58989. 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;
  58990. 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;
  58991. }
  58992. bBox._update(this.mesh._worldMatrix);
  58993. }
  58994. // place and scale the particle bouding sphere in the SPS local system, then update it
  58995. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58996. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58997. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58998. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58999. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59000. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59001. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59002. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59003. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59004. 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));
  59005. bSphere._update(this.mesh._worldMatrix);
  59006. }
  59007. // increment indexes for the next particle
  59008. index = idx + 3;
  59009. colorIndex = colidx + 4;
  59010. uvIndex = uvidx + 2;
  59011. }
  59012. // if the VBO must be updated
  59013. if (update) {
  59014. if (this._computeParticleColor) {
  59015. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59016. }
  59017. if (this._computeParticleTexture) {
  59018. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59019. }
  59020. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59021. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59022. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59023. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59024. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59025. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59026. for (var i = 0; i < this._normals32.length; i++) {
  59027. this._fixedNormal32[i] = this._normals32[i];
  59028. }
  59029. }
  59030. if (!this.mesh.areNormalsFrozen) {
  59031. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59032. }
  59033. }
  59034. if (this._depthSort && this._depthSortParticles) {
  59035. this.depthSortedParticles.sort(this._depthSortFunction);
  59036. var dspl = this.depthSortedParticles.length;
  59037. var sorted = 0;
  59038. var lind = 0;
  59039. var sind = 0;
  59040. var sid = 0;
  59041. for (sorted = 0; sorted < dspl; sorted++) {
  59042. lind = this.depthSortedParticles[sorted].indicesLength;
  59043. sind = this.depthSortedParticles[sorted].ind;
  59044. for (var i = 0; i < lind; i++) {
  59045. this._indices32[sid] = this._indices[sind + i];
  59046. sid++;
  59047. }
  59048. }
  59049. this.mesh.updateIndices(this._indices32);
  59050. }
  59051. }
  59052. if (this._computeBoundingBox) {
  59053. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59054. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59055. }
  59056. this.afterUpdateParticles(start, end, update);
  59057. return this;
  59058. };
  59059. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59060. this._halfroll = this._roll * 0.5;
  59061. this._halfpitch = this._pitch * 0.5;
  59062. this._halfyaw = this._yaw * 0.5;
  59063. this._sinRoll = Math.sin(this._halfroll);
  59064. this._cosRoll = Math.cos(this._halfroll);
  59065. this._sinPitch = Math.sin(this._halfpitch);
  59066. this._cosPitch = Math.cos(this._halfpitch);
  59067. this._sinYaw = Math.sin(this._halfyaw);
  59068. this._cosYaw = Math.cos(this._halfyaw);
  59069. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59070. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59071. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59072. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59073. };
  59074. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59075. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59076. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59077. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59078. this._rotMatrix.m[3] = 0;
  59079. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59080. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59081. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59082. this._rotMatrix.m[7] = 0;
  59083. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59084. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59085. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59086. this._rotMatrix.m[11] = 0;
  59087. this._rotMatrix.m[12] = 0;
  59088. this._rotMatrix.m[13] = 0;
  59089. this._rotMatrix.m[14] = 0;
  59090. this._rotMatrix.m[15] = 1.0;
  59091. };
  59092. /**
  59093. * Disposes the SPS.
  59094. */
  59095. SolidParticleSystem.prototype.dispose = function () {
  59096. this.mesh.dispose();
  59097. this.vars = null;
  59098. // drop references to internal big arrays for the GC
  59099. this._positions = null;
  59100. this._indices = null;
  59101. this._normals = null;
  59102. this._uvs = null;
  59103. this._colors = null;
  59104. this._indices32 = null;
  59105. this._positions32 = null;
  59106. this._normals32 = null;
  59107. this._fixedNormal32 = null;
  59108. this._uvs32 = null;
  59109. this._colors32 = null;
  59110. this.pickedParticles = null;
  59111. };
  59112. /**
  59113. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59114. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59115. * @returns the SPS.
  59116. */
  59117. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59118. if (!this._isVisibilityBoxLocked) {
  59119. this.mesh.refreshBoundingInfo();
  59120. }
  59121. return this;
  59122. };
  59123. /**
  59124. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59125. * @param size the size (float) of the visibility box
  59126. * note : this doesn't lock the SPS mesh bounding box.
  59127. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59128. */
  59129. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59130. var vis = size / 2;
  59131. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59132. };
  59133. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59134. /**
  59135. * Gets whether the SPS as always visible or not
  59136. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59137. */
  59138. get: function () {
  59139. return this._alwaysVisible;
  59140. },
  59141. /**
  59142. * Sets the SPS as always visible or not
  59143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59144. */
  59145. set: function (val) {
  59146. this._alwaysVisible = val;
  59147. this.mesh.alwaysSelectAsActiveMesh = val;
  59148. },
  59149. enumerable: true,
  59150. configurable: true
  59151. });
  59152. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59153. /**
  59154. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59156. */
  59157. get: function () {
  59158. return this._isVisibilityBoxLocked;
  59159. },
  59160. /**
  59161. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59162. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59163. */
  59164. set: function (val) {
  59165. this._isVisibilityBoxLocked = val;
  59166. var boundingInfo = this.mesh.getBoundingInfo();
  59167. boundingInfo.isLocked = val;
  59168. },
  59169. enumerable: true,
  59170. configurable: true
  59171. });
  59172. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59173. /**
  59174. * Gets if `setParticles()` computes the particle rotations or not.
  59175. * Default value : true. The SPS is faster when it's set to false.
  59176. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59177. */
  59178. get: function () {
  59179. return this._computeParticleRotation;
  59180. },
  59181. /**
  59182. * Tells to `setParticles()` to compute the particle rotations or not.
  59183. * Default value : true. The SPS is faster when it's set to false.
  59184. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59185. */
  59186. set: function (val) {
  59187. this._computeParticleRotation = val;
  59188. },
  59189. enumerable: true,
  59190. configurable: true
  59191. });
  59192. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59193. /**
  59194. * Gets if `setParticles()` computes the particle colors or not.
  59195. * Default value : true. The SPS is faster when it's set to false.
  59196. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59197. */
  59198. get: function () {
  59199. return this._computeParticleColor;
  59200. },
  59201. /**
  59202. * Tells to `setParticles()` to compute the particle colors or not.
  59203. * Default value : true. The SPS is faster when it's set to false.
  59204. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59205. */
  59206. set: function (val) {
  59207. this._computeParticleColor = val;
  59208. },
  59209. enumerable: true,
  59210. configurable: true
  59211. });
  59212. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59213. /**
  59214. * Gets if `setParticles()` computes the particle textures or not.
  59215. * Default value : true. The SPS is faster when it's set to false.
  59216. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59217. */
  59218. get: function () {
  59219. return this._computeParticleTexture;
  59220. },
  59221. set: function (val) {
  59222. this._computeParticleTexture = val;
  59223. },
  59224. enumerable: true,
  59225. configurable: true
  59226. });
  59227. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59228. /**
  59229. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59230. * Default value : false. The SPS is faster when it's set to false.
  59231. * Note : the particle custom vertex positions aren't stored values.
  59232. */
  59233. get: function () {
  59234. return this._computeParticleVertex;
  59235. },
  59236. /**
  59237. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59238. * Default value : false. The SPS is faster when it's set to false.
  59239. * Note : the particle custom vertex positions aren't stored values.
  59240. */
  59241. set: function (val) {
  59242. this._computeParticleVertex = val;
  59243. },
  59244. enumerable: true,
  59245. configurable: true
  59246. });
  59247. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59248. /**
  59249. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59250. */
  59251. get: function () {
  59252. return this._computeBoundingBox;
  59253. },
  59254. /**
  59255. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59256. */
  59257. set: function (val) {
  59258. this._computeBoundingBox = val;
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59264. /**
  59265. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59266. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59267. * Default : `true`
  59268. */
  59269. get: function () {
  59270. return this._depthSortParticles;
  59271. },
  59272. /**
  59273. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59274. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59275. * Default : `true`
  59276. */
  59277. set: function (val) {
  59278. this._depthSortParticles = val;
  59279. },
  59280. enumerable: true,
  59281. configurable: true
  59282. });
  59283. // =======================================================================
  59284. // Particle behavior logic
  59285. // these following methods may be overwritten by the user to fit his needs
  59286. /**
  59287. * This function does nothing. It may be overwritten to set all the particle first values.
  59288. * The SPS doesn't call this function, you may have to call it by your own.
  59289. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59290. */
  59291. SolidParticleSystem.prototype.initParticles = function () {
  59292. };
  59293. /**
  59294. * This function does nothing. It may be overwritten to recycle a particle.
  59295. * The SPS doesn't call this function, you may have to call it by your own.
  59296. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59297. * @param particle The particle to recycle
  59298. * @returns the recycled particle
  59299. */
  59300. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59301. return particle;
  59302. };
  59303. /**
  59304. * Updates a particle : this function should be overwritten by the user.
  59305. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59307. * @example : just set a particle position or velocity and recycle conditions
  59308. * @param particle The particle to update
  59309. * @returns the updated particle
  59310. */
  59311. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59312. return particle;
  59313. };
  59314. /**
  59315. * Updates a vertex of a particle : it can be overwritten by the user.
  59316. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59317. * @param particle the current particle
  59318. * @param vertex the current index of the current particle
  59319. * @param pt the index of the current vertex in the particle shape
  59320. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59321. * @example : just set a vertex particle position
  59322. * @returns the updated vertex
  59323. */
  59324. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59325. return vertex;
  59326. };
  59327. /**
  59328. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59329. * This does nothing and may be overwritten by the user.
  59330. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59331. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59332. * @param update the boolean update value actually passed to setParticles()
  59333. */
  59334. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59335. };
  59336. /**
  59337. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59338. * This will be passed three parameters.
  59339. * This does nothing and may be overwritten by the user.
  59340. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59341. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59342. * @param update the boolean update value actually passed to setParticles()
  59343. */
  59344. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59345. };
  59346. return SolidParticleSystem;
  59347. }());
  59348. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59349. })(BABYLON || (BABYLON = {}));
  59350. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59351. var BABYLON;
  59352. (function (BABYLON) {
  59353. var ShaderMaterial = /** @class */ (function (_super) {
  59354. __extends(ShaderMaterial, _super);
  59355. function ShaderMaterial(name, scene, shaderPath, options) {
  59356. var _this = _super.call(this, name, scene) || this;
  59357. _this._textures = {};
  59358. _this._textureArrays = {};
  59359. _this._floats = {};
  59360. _this._ints = {};
  59361. _this._floatsArrays = {};
  59362. _this._colors3 = {};
  59363. _this._colors3Arrays = {};
  59364. _this._colors4 = {};
  59365. _this._vectors2 = {};
  59366. _this._vectors3 = {};
  59367. _this._vectors4 = {};
  59368. _this._matrices = {};
  59369. _this._matrices3x3 = {};
  59370. _this._matrices2x2 = {};
  59371. _this._vectors2Arrays = {};
  59372. _this._vectors3Arrays = {};
  59373. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59374. _this._shaderPath = shaderPath;
  59375. options.needAlphaBlending = options.needAlphaBlending || false;
  59376. options.needAlphaTesting = options.needAlphaTesting || false;
  59377. options.attributes = options.attributes || ["position", "normal", "uv"];
  59378. options.uniforms = options.uniforms || ["worldViewProjection"];
  59379. options.uniformBuffers = options.uniformBuffers || [];
  59380. options.samplers = options.samplers || [];
  59381. options.defines = options.defines || [];
  59382. _this._options = options;
  59383. return _this;
  59384. }
  59385. ShaderMaterial.prototype.getClassName = function () {
  59386. return "ShaderMaterial";
  59387. };
  59388. ShaderMaterial.prototype.needAlphaBlending = function () {
  59389. return this._options.needAlphaBlending;
  59390. };
  59391. ShaderMaterial.prototype.needAlphaTesting = function () {
  59392. return this._options.needAlphaTesting;
  59393. };
  59394. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59395. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59396. this._options.uniforms.push(uniformName);
  59397. }
  59398. };
  59399. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59400. if (this._options.samplers.indexOf(name) === -1) {
  59401. this._options.samplers.push(name);
  59402. }
  59403. this._textures[name] = texture;
  59404. return this;
  59405. };
  59406. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59407. if (this._options.samplers.indexOf(name) === -1) {
  59408. this._options.samplers.push(name);
  59409. }
  59410. this._checkUniform(name);
  59411. this._textureArrays[name] = textures;
  59412. return this;
  59413. };
  59414. ShaderMaterial.prototype.setFloat = function (name, value) {
  59415. this._checkUniform(name);
  59416. this._floats[name] = value;
  59417. return this;
  59418. };
  59419. ShaderMaterial.prototype.setInt = function (name, value) {
  59420. this._checkUniform(name);
  59421. this._ints[name] = value;
  59422. return this;
  59423. };
  59424. ShaderMaterial.prototype.setFloats = function (name, value) {
  59425. this._checkUniform(name);
  59426. this._floatsArrays[name] = value;
  59427. return this;
  59428. };
  59429. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59430. this._checkUniform(name);
  59431. this._colors3[name] = value;
  59432. return this;
  59433. };
  59434. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59435. this._checkUniform(name);
  59436. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59437. color.toArray(arr, arr.length);
  59438. return arr;
  59439. }, []);
  59440. return this;
  59441. };
  59442. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59443. this._checkUniform(name);
  59444. this._colors4[name] = value;
  59445. return this;
  59446. };
  59447. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59448. this._checkUniform(name);
  59449. this._vectors2[name] = value;
  59450. return this;
  59451. };
  59452. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59453. this._checkUniform(name);
  59454. this._vectors3[name] = value;
  59455. return this;
  59456. };
  59457. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59458. this._checkUniform(name);
  59459. this._vectors4[name] = value;
  59460. return this;
  59461. };
  59462. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59463. this._checkUniform(name);
  59464. this._matrices[name] = value;
  59465. return this;
  59466. };
  59467. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59468. this._checkUniform(name);
  59469. this._matrices3x3[name] = value;
  59470. return this;
  59471. };
  59472. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59473. this._checkUniform(name);
  59474. this._matrices2x2[name] = value;
  59475. return this;
  59476. };
  59477. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59478. this._checkUniform(name);
  59479. this._vectors2Arrays[name] = value;
  59480. return this;
  59481. };
  59482. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59483. this._checkUniform(name);
  59484. this._vectors3Arrays[name] = value;
  59485. return this;
  59486. };
  59487. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59488. if (!mesh) {
  59489. return true;
  59490. }
  59491. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59492. return false;
  59493. }
  59494. return false;
  59495. };
  59496. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59497. var scene = this.getScene();
  59498. var engine = scene.getEngine();
  59499. if (!this.checkReadyOnEveryCall) {
  59500. if (this._renderId === scene.getRenderId()) {
  59501. if (this._checkCache(scene, mesh, useInstances)) {
  59502. return true;
  59503. }
  59504. }
  59505. }
  59506. // Instances
  59507. var defines = [];
  59508. var attribs = [];
  59509. var fallbacks = new BABYLON.EffectFallbacks();
  59510. if (useInstances) {
  59511. defines.push("#define INSTANCES");
  59512. }
  59513. for (var index = 0; index < this._options.defines.length; index++) {
  59514. defines.push(this._options.defines[index]);
  59515. }
  59516. for (var index = 0; index < this._options.attributes.length; index++) {
  59517. attribs.push(this._options.attributes[index]);
  59518. }
  59519. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59520. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59521. defines.push("#define VERTEXCOLOR");
  59522. }
  59523. // Bones
  59524. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59527. if (mesh.numBoneInfluencers > 4) {
  59528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59530. }
  59531. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59532. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59533. fallbacks.addCPUSkinningFallback(0, mesh);
  59534. if (this._options.uniforms.indexOf("mBones") === -1) {
  59535. this._options.uniforms.push("mBones");
  59536. }
  59537. }
  59538. else {
  59539. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59540. }
  59541. // Textures
  59542. for (var name in this._textures) {
  59543. if (!this._textures[name].isReady()) {
  59544. return false;
  59545. }
  59546. }
  59547. // Alpha test
  59548. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59549. defines.push("#define ALPHATEST");
  59550. }
  59551. var previousEffect = this._effect;
  59552. var join = defines.join("\n");
  59553. this._effect = engine.createEffect(this._shaderPath, {
  59554. attributes: attribs,
  59555. uniformsNames: this._options.uniforms,
  59556. uniformBuffersNames: this._options.uniformBuffers,
  59557. samplers: this._options.samplers,
  59558. defines: join,
  59559. fallbacks: fallbacks,
  59560. onCompiled: this.onCompiled,
  59561. onError: this.onError
  59562. }, engine);
  59563. if (!this._effect.isReady()) {
  59564. return false;
  59565. }
  59566. if (previousEffect !== this._effect) {
  59567. scene.resetCachedMaterial();
  59568. }
  59569. this._renderId = scene.getRenderId();
  59570. return true;
  59571. };
  59572. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59573. var scene = this.getScene();
  59574. if (!this._effect) {
  59575. return;
  59576. }
  59577. if (this._options.uniforms.indexOf("world") !== -1) {
  59578. this._effect.setMatrix("world", world);
  59579. }
  59580. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59581. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59582. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59583. }
  59584. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59585. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59586. }
  59587. };
  59588. ShaderMaterial.prototype.bind = function (world, mesh) {
  59589. // Std values
  59590. this.bindOnlyWorldMatrix(world);
  59591. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59592. if (this._options.uniforms.indexOf("view") !== -1) {
  59593. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59594. }
  59595. if (this._options.uniforms.indexOf("projection") !== -1) {
  59596. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59597. }
  59598. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59599. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59600. }
  59601. // Bones
  59602. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59603. var name;
  59604. // Texture
  59605. for (name in this._textures) {
  59606. this._effect.setTexture(name, this._textures[name]);
  59607. }
  59608. // Texture arrays
  59609. for (name in this._textureArrays) {
  59610. this._effect.setTextureArray(name, this._textureArrays[name]);
  59611. }
  59612. // Int
  59613. for (name in this._ints) {
  59614. this._effect.setInt(name, this._ints[name]);
  59615. }
  59616. // Float
  59617. for (name in this._floats) {
  59618. this._effect.setFloat(name, this._floats[name]);
  59619. }
  59620. // Floats
  59621. for (name in this._floatsArrays) {
  59622. this._effect.setArray(name, this._floatsArrays[name]);
  59623. }
  59624. // Color3
  59625. for (name in this._colors3) {
  59626. this._effect.setColor3(name, this._colors3[name]);
  59627. }
  59628. for (name in this._colors3Arrays) {
  59629. this._effect.setArray3(name, this._colors3Arrays[name]);
  59630. }
  59631. // Color4
  59632. for (name in this._colors4) {
  59633. var color = this._colors4[name];
  59634. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59635. }
  59636. // Vector2
  59637. for (name in this._vectors2) {
  59638. this._effect.setVector2(name, this._vectors2[name]);
  59639. }
  59640. // Vector3
  59641. for (name in this._vectors3) {
  59642. this._effect.setVector3(name, this._vectors3[name]);
  59643. }
  59644. // Vector4
  59645. for (name in this._vectors4) {
  59646. this._effect.setVector4(name, this._vectors4[name]);
  59647. }
  59648. // Matrix
  59649. for (name in this._matrices) {
  59650. this._effect.setMatrix(name, this._matrices[name]);
  59651. }
  59652. // Matrix 3x3
  59653. for (name in this._matrices3x3) {
  59654. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59655. }
  59656. // Matrix 2x2
  59657. for (name in this._matrices2x2) {
  59658. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59659. }
  59660. // Vector2Array
  59661. for (name in this._vectors2Arrays) {
  59662. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59663. }
  59664. // Vector3Array
  59665. for (name in this._vectors3Arrays) {
  59666. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59667. }
  59668. }
  59669. this._afterBind(mesh);
  59670. };
  59671. ShaderMaterial.prototype.getActiveTextures = function () {
  59672. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59673. for (var name in this._textures) {
  59674. activeTextures.push(this._textures[name]);
  59675. }
  59676. for (var name in this._textureArrays) {
  59677. var array = this._textureArrays[name];
  59678. for (var index = 0; index < array.length; index++) {
  59679. activeTextures.push(array[index]);
  59680. }
  59681. }
  59682. return activeTextures;
  59683. };
  59684. ShaderMaterial.prototype.hasTexture = function (texture) {
  59685. if (_super.prototype.hasTexture.call(this, texture)) {
  59686. return true;
  59687. }
  59688. for (var name in this._textures) {
  59689. if (this._textures[name] === texture) {
  59690. return true;
  59691. }
  59692. }
  59693. for (var name in this._textureArrays) {
  59694. var array = this._textureArrays[name];
  59695. for (var index = 0; index < array.length; index++) {
  59696. if (array[index] === texture) {
  59697. return true;
  59698. }
  59699. }
  59700. }
  59701. return false;
  59702. };
  59703. ShaderMaterial.prototype.clone = function (name) {
  59704. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59705. return newShaderMaterial;
  59706. };
  59707. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59708. if (forceDisposeTextures) {
  59709. var name;
  59710. for (name in this._textures) {
  59711. this._textures[name].dispose();
  59712. }
  59713. for (name in this._textureArrays) {
  59714. var array = this._textureArrays[name];
  59715. for (var index = 0; index < array.length; index++) {
  59716. array[index].dispose();
  59717. }
  59718. }
  59719. }
  59720. this._textures = {};
  59721. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59722. };
  59723. ShaderMaterial.prototype.serialize = function () {
  59724. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59725. serializationObject.customType = "BABYLON.ShaderMaterial";
  59726. serializationObject.options = this._options;
  59727. serializationObject.shaderPath = this._shaderPath;
  59728. var name;
  59729. // Texture
  59730. serializationObject.textures = {};
  59731. for (name in this._textures) {
  59732. serializationObject.textures[name] = this._textures[name].serialize();
  59733. }
  59734. // Texture arrays
  59735. serializationObject.textureArrays = {};
  59736. for (name in this._textureArrays) {
  59737. serializationObject.textureArrays[name] = [];
  59738. var array = this._textureArrays[name];
  59739. for (var index = 0; index < array.length; index++) {
  59740. serializationObject.textureArrays[name].push(array[index].serialize());
  59741. }
  59742. }
  59743. // Float
  59744. serializationObject.floats = {};
  59745. for (name in this._floats) {
  59746. serializationObject.floats[name] = this._floats[name];
  59747. }
  59748. // Float s
  59749. serializationObject.FloatArrays = {};
  59750. for (name in this._floatsArrays) {
  59751. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59752. }
  59753. // Color3
  59754. serializationObject.colors3 = {};
  59755. for (name in this._colors3) {
  59756. serializationObject.colors3[name] = this._colors3[name].asArray();
  59757. }
  59758. // Color3 array
  59759. serializationObject.colors3Arrays = {};
  59760. for (name in this._colors3Arrays) {
  59761. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59762. }
  59763. // Color4
  59764. serializationObject.colors4 = {};
  59765. for (name in this._colors4) {
  59766. serializationObject.colors4[name] = this._colors4[name].asArray();
  59767. }
  59768. // Vector2
  59769. serializationObject.vectors2 = {};
  59770. for (name in this._vectors2) {
  59771. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59772. }
  59773. // Vector3
  59774. serializationObject.vectors3 = {};
  59775. for (name in this._vectors3) {
  59776. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59777. }
  59778. // Vector4
  59779. serializationObject.vectors4 = {};
  59780. for (name in this._vectors4) {
  59781. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59782. }
  59783. // Matrix
  59784. serializationObject.matrices = {};
  59785. for (name in this._matrices) {
  59786. serializationObject.matrices[name] = this._matrices[name].asArray();
  59787. }
  59788. // Matrix 3x3
  59789. serializationObject.matrices3x3 = {};
  59790. for (name in this._matrices3x3) {
  59791. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59792. }
  59793. // Matrix 2x2
  59794. serializationObject.matrices2x2 = {};
  59795. for (name in this._matrices2x2) {
  59796. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59797. }
  59798. // Vector2Array
  59799. serializationObject.vectors2Arrays = {};
  59800. for (name in this._vectors2Arrays) {
  59801. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59802. }
  59803. // Vector3Array
  59804. serializationObject.vectors3Arrays = {};
  59805. for (name in this._vectors3Arrays) {
  59806. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59807. }
  59808. return serializationObject;
  59809. };
  59810. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59811. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59812. var name;
  59813. // Texture
  59814. for (name in source.textures) {
  59815. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59816. }
  59817. // Texture arrays
  59818. for (name in source.textureArrays) {
  59819. var array = source.textureArrays[name];
  59820. var textureArray = new Array();
  59821. for (var index = 0; index < array.length; index++) {
  59822. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59823. }
  59824. material.setTextureArray(name, textureArray);
  59825. }
  59826. // Float
  59827. for (name in source.floats) {
  59828. material.setFloat(name, source.floats[name]);
  59829. }
  59830. // Float s
  59831. for (name in source.floatsArrays) {
  59832. material.setFloats(name, source.floatsArrays[name]);
  59833. }
  59834. // Color3
  59835. for (name in source.colors3) {
  59836. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59837. }
  59838. // Color3 arrays
  59839. for (name in source.colors3Arrays) {
  59840. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59841. if (i % 3 === 0) {
  59842. arr.push([num]);
  59843. }
  59844. else {
  59845. arr[arr.length - 1].push(num);
  59846. }
  59847. return arr;
  59848. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59849. material.setColor3Array(name, colors);
  59850. }
  59851. // Color4
  59852. for (name in source.colors4) {
  59853. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59854. }
  59855. // Vector2
  59856. for (name in source.vectors2) {
  59857. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59858. }
  59859. // Vector3
  59860. for (name in source.vectors3) {
  59861. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59862. }
  59863. // Vector4
  59864. for (name in source.vectors4) {
  59865. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59866. }
  59867. // Matrix
  59868. for (name in source.matrices) {
  59869. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59870. }
  59871. // Matrix 3x3
  59872. for (name in source.matrices3x3) {
  59873. material.setMatrix3x3(name, source.matrices3x3[name]);
  59874. }
  59875. // Matrix 2x2
  59876. for (name in source.matrices2x2) {
  59877. material.setMatrix2x2(name, source.matrices2x2[name]);
  59878. }
  59879. // Vector2Array
  59880. for (name in source.vectors2Arrays) {
  59881. material.setArray2(name, source.vectors2Arrays[name]);
  59882. }
  59883. // Vector3Array
  59884. for (name in source.vectors3Arrays) {
  59885. material.setArray3(name, source.vectors3Arrays[name]);
  59886. }
  59887. return material;
  59888. };
  59889. return ShaderMaterial;
  59890. }(BABYLON.Material));
  59891. BABYLON.ShaderMaterial = ShaderMaterial;
  59892. })(BABYLON || (BABYLON = {}));
  59893. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59894. var BABYLON;
  59895. (function (BABYLON) {
  59896. var GroundMesh = /** @class */ (function (_super) {
  59897. __extends(GroundMesh, _super);
  59898. function GroundMesh(name, scene) {
  59899. var _this = _super.call(this, name, scene) || this;
  59900. _this.generateOctree = false;
  59901. return _this;
  59902. }
  59903. GroundMesh.prototype.getClassName = function () {
  59904. return "GroundMesh";
  59905. };
  59906. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59907. get: function () {
  59908. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59909. },
  59910. enumerable: true,
  59911. configurable: true
  59912. });
  59913. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59914. get: function () {
  59915. return this._subdivisionsX;
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59921. get: function () {
  59922. return this._subdivisionsY;
  59923. },
  59924. enumerable: true,
  59925. configurable: true
  59926. });
  59927. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59928. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59929. this._subdivisionsX = chunksCount;
  59930. this._subdivisionsY = chunksCount;
  59931. this.subdivide(chunksCount);
  59932. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59933. };
  59934. /**
  59935. * Returns a height (y) value in the Worl system :
  59936. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59937. * Returns the ground y position if (x, z) are outside the ground surface.
  59938. */
  59939. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59940. var world = this.getWorldMatrix();
  59941. var invMat = BABYLON.Tmp.Matrix[5];
  59942. world.invertToRef(invMat);
  59943. var tmpVect = BABYLON.Tmp.Vector3[8];
  59944. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59945. x = tmpVect.x;
  59946. z = tmpVect.z;
  59947. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59948. return this.position.y;
  59949. }
  59950. if (!this._heightQuads || this._heightQuads.length == 0) {
  59951. this._initHeightQuads();
  59952. this._computeHeightQuads();
  59953. }
  59954. var facet = this._getFacetAt(x, z);
  59955. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59956. // return y in the World system
  59957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59958. return tmpVect.y;
  59959. };
  59960. /**
  59961. * Returns a normalized vector (Vector3) orthogonal to the ground
  59962. * at the ground coordinates (x, z) expressed in the World system.
  59963. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59964. */
  59965. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59966. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59967. this.getNormalAtCoordinatesToRef(x, z, normal);
  59968. return normal;
  59969. };
  59970. /**
  59971. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59972. * at the ground coordinates (x, z) expressed in the World system.
  59973. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59974. * Returns the GroundMesh.
  59975. */
  59976. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59977. var world = this.getWorldMatrix();
  59978. var tmpMat = BABYLON.Tmp.Matrix[5];
  59979. world.invertToRef(tmpMat);
  59980. var tmpVect = BABYLON.Tmp.Vector3[8];
  59981. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59982. x = tmpVect.x;
  59983. z = tmpVect.z;
  59984. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59985. return this;
  59986. }
  59987. if (!this._heightQuads || this._heightQuads.length == 0) {
  59988. this._initHeightQuads();
  59989. this._computeHeightQuads();
  59990. }
  59991. var facet = this._getFacetAt(x, z);
  59992. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59993. return this;
  59994. };
  59995. /**
  59996. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59997. * if the ground has been updated.
  59998. * This can be used in the render loop.
  59999. * Returns the GroundMesh.
  60000. */
  60001. GroundMesh.prototype.updateCoordinateHeights = function () {
  60002. if (!this._heightQuads || this._heightQuads.length == 0) {
  60003. this._initHeightQuads();
  60004. }
  60005. this._computeHeightQuads();
  60006. return this;
  60007. };
  60008. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60009. GroundMesh.prototype._getFacetAt = function (x, z) {
  60010. // retrieve col and row from x, z coordinates in the ground local system
  60011. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60012. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60013. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60014. var facet;
  60015. if (z < quad.slope.x * x + quad.slope.y) {
  60016. facet = quad.facet1;
  60017. }
  60018. else {
  60019. facet = quad.facet2;
  60020. }
  60021. return facet;
  60022. };
  60023. // Creates and populates the heightMap array with "facet" elements :
  60024. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60025. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60026. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60027. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60028. // Returns the GroundMesh.
  60029. GroundMesh.prototype._initHeightQuads = function () {
  60030. var subdivisionsX = this._subdivisionsX;
  60031. var subdivisionsY = this._subdivisionsY;
  60032. this._heightQuads = new Array();
  60033. for (var row = 0; row < subdivisionsY; row++) {
  60034. for (var col = 0; col < subdivisionsX; col++) {
  60035. 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) };
  60036. this._heightQuads[row * subdivisionsX + col] = quad;
  60037. }
  60038. }
  60039. return this;
  60040. };
  60041. // Compute each quad element values and update the the heightMap array :
  60042. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60043. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60044. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60045. // Returns the GroundMesh.
  60046. GroundMesh.prototype._computeHeightQuads = function () {
  60047. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60048. if (!positions) {
  60049. return this;
  60050. }
  60051. var v1 = BABYLON.Tmp.Vector3[3];
  60052. var v2 = BABYLON.Tmp.Vector3[2];
  60053. var v3 = BABYLON.Tmp.Vector3[1];
  60054. var v4 = BABYLON.Tmp.Vector3[0];
  60055. var v1v2 = BABYLON.Tmp.Vector3[4];
  60056. var v1v3 = BABYLON.Tmp.Vector3[5];
  60057. var v1v4 = BABYLON.Tmp.Vector3[6];
  60058. var norm1 = BABYLON.Tmp.Vector3[7];
  60059. var norm2 = BABYLON.Tmp.Vector3[8];
  60060. var i = 0;
  60061. var j = 0;
  60062. var k = 0;
  60063. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60064. var h = 0;
  60065. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60066. var d2 = 0;
  60067. var subdivisionsX = this._subdivisionsX;
  60068. var subdivisionsY = this._subdivisionsY;
  60069. for (var row = 0; row < subdivisionsY; row++) {
  60070. for (var col = 0; col < subdivisionsX; col++) {
  60071. i = col * 3;
  60072. j = row * (subdivisionsX + 1) * 3;
  60073. k = (row + 1) * (subdivisionsX + 1) * 3;
  60074. v1.x = positions[j + i];
  60075. v1.y = positions[j + i + 1];
  60076. v1.z = positions[j + i + 2];
  60077. v2.x = positions[j + i + 3];
  60078. v2.y = positions[j + i + 4];
  60079. v2.z = positions[j + i + 5];
  60080. v3.x = positions[k + i];
  60081. v3.y = positions[k + i + 1];
  60082. v3.z = positions[k + i + 2];
  60083. v4.x = positions[k + i + 3];
  60084. v4.y = positions[k + i + 4];
  60085. v4.z = positions[k + i + 5];
  60086. // 2D slope V1V4
  60087. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60088. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60089. // facet equations :
  60090. // we compute each facet normal vector
  60091. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60092. // we compute the value d by applying the equation to v1 which belongs to the plane
  60093. // then we store the facet equation in a Vector4
  60094. v2.subtractToRef(v1, v1v2);
  60095. v3.subtractToRef(v1, v1v3);
  60096. v4.subtractToRef(v1, v1v4);
  60097. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60098. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60099. norm1.normalize();
  60100. norm2.normalize();
  60101. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60102. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60103. var quad = this._heightQuads[row * subdivisionsX + col];
  60104. quad.slope.copyFromFloats(cd, h);
  60105. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60106. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60107. }
  60108. }
  60109. return this;
  60110. };
  60111. GroundMesh.prototype.serialize = function (serializationObject) {
  60112. _super.prototype.serialize.call(this, serializationObject);
  60113. serializationObject.subdivisionsX = this._subdivisionsX;
  60114. serializationObject.subdivisionsY = this._subdivisionsY;
  60115. serializationObject.minX = this._minX;
  60116. serializationObject.maxX = this._maxX;
  60117. serializationObject.minZ = this._minZ;
  60118. serializationObject.maxZ = this._maxZ;
  60119. serializationObject.width = this._width;
  60120. serializationObject.height = this._height;
  60121. };
  60122. GroundMesh.Parse = function (parsedMesh, scene) {
  60123. var result = new GroundMesh(parsedMesh.name, scene);
  60124. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60125. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60126. result._minX = parsedMesh.minX;
  60127. result._maxX = parsedMesh.maxX;
  60128. result._minZ = parsedMesh.minZ;
  60129. result._maxZ = parsedMesh.maxZ;
  60130. result._width = parsedMesh.width;
  60131. result._height = parsedMesh.height;
  60132. return result;
  60133. };
  60134. return GroundMesh;
  60135. }(BABYLON.Mesh));
  60136. BABYLON.GroundMesh = GroundMesh;
  60137. })(BABYLON || (BABYLON = {}));
  60138. //# sourceMappingURL=babylon.groundMesh.js.map
  60139. var BABYLON;
  60140. (function (BABYLON) {
  60141. /**
  60142. * Creates an instance based on a source mesh.
  60143. */
  60144. var InstancedMesh = /** @class */ (function (_super) {
  60145. __extends(InstancedMesh, _super);
  60146. function InstancedMesh(name, source) {
  60147. var _this = _super.call(this, name, source.getScene()) || this;
  60148. source.instances.push(_this);
  60149. _this._sourceMesh = source;
  60150. _this.position.copyFrom(source.position);
  60151. _this.rotation.copyFrom(source.rotation);
  60152. _this.scaling.copyFrom(source.scaling);
  60153. if (source.rotationQuaternion) {
  60154. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60155. }
  60156. _this.infiniteDistance = source.infiniteDistance;
  60157. _this.setPivotMatrix(source.getPivotMatrix());
  60158. _this.refreshBoundingInfo();
  60159. _this._syncSubMeshes();
  60160. return _this;
  60161. }
  60162. /**
  60163. * Returns the string "InstancedMesh".
  60164. */
  60165. InstancedMesh.prototype.getClassName = function () {
  60166. return "InstancedMesh";
  60167. };
  60168. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60169. // Methods
  60170. get: function () {
  60171. return this._sourceMesh.receiveShadows;
  60172. },
  60173. enumerable: true,
  60174. configurable: true
  60175. });
  60176. Object.defineProperty(InstancedMesh.prototype, "material", {
  60177. get: function () {
  60178. return this._sourceMesh.material;
  60179. },
  60180. enumerable: true,
  60181. configurable: true
  60182. });
  60183. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60184. get: function () {
  60185. return this._sourceMesh.visibility;
  60186. },
  60187. enumerable: true,
  60188. configurable: true
  60189. });
  60190. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60191. get: function () {
  60192. return this._sourceMesh.skeleton;
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60198. get: function () {
  60199. return this._sourceMesh.renderingGroupId;
  60200. },
  60201. set: function (value) {
  60202. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60203. return;
  60204. }
  60205. //no-op with warning
  60206. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60207. },
  60208. enumerable: true,
  60209. configurable: true
  60210. });
  60211. /**
  60212. * Returns the total number of vertices (integer).
  60213. */
  60214. InstancedMesh.prototype.getTotalVertices = function () {
  60215. return this._sourceMesh.getTotalVertices();
  60216. };
  60217. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60218. get: function () {
  60219. return this._sourceMesh;
  60220. },
  60221. enumerable: true,
  60222. configurable: true
  60223. });
  60224. /**
  60225. * Is this node ready to be used/rendered
  60226. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60227. * @return {boolean} is it ready
  60228. */
  60229. InstancedMesh.prototype.isReady = function (completeCheck) {
  60230. if (completeCheck === void 0) { completeCheck = false; }
  60231. return this._sourceMesh.isReady(completeCheck, true);
  60232. };
  60233. /**
  60234. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60235. */
  60236. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60237. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60238. };
  60239. /**
  60240. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60241. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60242. * The `data` are either a numeric array either a Float32Array.
  60243. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60244. * 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).
  60245. * Note that a new underlying VertexBuffer object is created each call.
  60246. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60247. *
  60248. * Possible `kind` values :
  60249. * - BABYLON.VertexBuffer.PositionKind
  60250. * - BABYLON.VertexBuffer.UVKind
  60251. * - BABYLON.VertexBuffer.UV2Kind
  60252. * - BABYLON.VertexBuffer.UV3Kind
  60253. * - BABYLON.VertexBuffer.UV4Kind
  60254. * - BABYLON.VertexBuffer.UV5Kind
  60255. * - BABYLON.VertexBuffer.UV6Kind
  60256. * - BABYLON.VertexBuffer.ColorKind
  60257. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60258. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60259. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60260. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60261. *
  60262. * Returns the Mesh.
  60263. */
  60264. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60265. if (this.sourceMesh) {
  60266. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60267. }
  60268. return this.sourceMesh;
  60269. };
  60270. /**
  60271. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60272. * If the mesh has no geometry, it is simply returned as it is.
  60273. * The `data` are either a numeric array either a Float32Array.
  60274. * No new underlying VertexBuffer object is created.
  60275. * 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.
  60276. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60277. *
  60278. * Possible `kind` values :
  60279. * - BABYLON.VertexBuffer.PositionKind
  60280. * - BABYLON.VertexBuffer.UVKind
  60281. * - BABYLON.VertexBuffer.UV2Kind
  60282. * - BABYLON.VertexBuffer.UV3Kind
  60283. * - BABYLON.VertexBuffer.UV4Kind
  60284. * - BABYLON.VertexBuffer.UV5Kind
  60285. * - BABYLON.VertexBuffer.UV6Kind
  60286. * - BABYLON.VertexBuffer.ColorKind
  60287. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60288. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60289. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60290. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60291. *
  60292. * Returns the Mesh.
  60293. */
  60294. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60295. if (this.sourceMesh) {
  60296. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60297. }
  60298. return this.sourceMesh;
  60299. };
  60300. /**
  60301. * Sets the mesh indices.
  60302. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60303. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60304. * This method creates a new index buffer each call.
  60305. * Returns the Mesh.
  60306. */
  60307. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60308. if (totalVertices === void 0) { totalVertices = null; }
  60309. if (this.sourceMesh) {
  60310. this.sourceMesh.setIndices(indices, totalVertices);
  60311. }
  60312. return this.sourceMesh;
  60313. };
  60314. /**
  60315. * Boolean : True if the mesh owns the requested kind of data.
  60316. */
  60317. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60318. return this._sourceMesh.isVerticesDataPresent(kind);
  60319. };
  60320. /**
  60321. * Returns an array of indices (IndicesArray).
  60322. */
  60323. InstancedMesh.prototype.getIndices = function () {
  60324. return this._sourceMesh.getIndices();
  60325. };
  60326. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60327. get: function () {
  60328. return this._sourceMesh._positions;
  60329. },
  60330. enumerable: true,
  60331. configurable: true
  60332. });
  60333. /**
  60334. * Sets a new updated BoundingInfo to the mesh.
  60335. * Returns the mesh.
  60336. */
  60337. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60338. var meshBB = this._sourceMesh.getBoundingInfo();
  60339. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60340. this._updateBoundingInfo();
  60341. return this;
  60342. };
  60343. InstancedMesh.prototype._preActivate = function () {
  60344. if (this._currentLOD) {
  60345. this._currentLOD._preActivate();
  60346. }
  60347. return this;
  60348. };
  60349. InstancedMesh.prototype._activate = function (renderId) {
  60350. if (this._currentLOD) {
  60351. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60352. }
  60353. return this;
  60354. };
  60355. /**
  60356. * Returns the current associated LOD AbstractMesh.
  60357. */
  60358. InstancedMesh.prototype.getLOD = function (camera) {
  60359. if (!camera) {
  60360. return this;
  60361. }
  60362. var boundingInfo = this.getBoundingInfo();
  60363. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60364. if (this._currentLOD === this.sourceMesh) {
  60365. return this;
  60366. }
  60367. return this._currentLOD;
  60368. };
  60369. InstancedMesh.prototype._syncSubMeshes = function () {
  60370. this.releaseSubMeshes();
  60371. if (this._sourceMesh.subMeshes) {
  60372. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60373. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60374. }
  60375. }
  60376. return this;
  60377. };
  60378. InstancedMesh.prototype._generatePointsArray = function () {
  60379. return this._sourceMesh._generatePointsArray();
  60380. };
  60381. /**
  60382. * Creates a new InstancedMesh from the current mesh.
  60383. * - name (string) : the cloned mesh name
  60384. * - newParent (optional Node) : the optional Node to parent the clone to.
  60385. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60386. *
  60387. * Returns the clone.
  60388. */
  60389. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60390. var result = this._sourceMesh.createInstance(name);
  60391. // Deep copy
  60392. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60393. // Bounding info
  60394. this.refreshBoundingInfo();
  60395. // Parent
  60396. if (newParent) {
  60397. result.parent = newParent;
  60398. }
  60399. if (!doNotCloneChildren) {
  60400. // Children
  60401. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60402. var mesh = this.getScene().meshes[index];
  60403. if (mesh.parent === this) {
  60404. mesh.clone(mesh.name, result);
  60405. }
  60406. }
  60407. }
  60408. result.computeWorldMatrix(true);
  60409. return result;
  60410. };
  60411. /**
  60412. * Disposes the InstancedMesh.
  60413. * Returns nothing.
  60414. */
  60415. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60417. // Remove from mesh
  60418. var index = this._sourceMesh.instances.indexOf(this);
  60419. this._sourceMesh.instances.splice(index, 1);
  60420. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60421. };
  60422. return InstancedMesh;
  60423. }(BABYLON.AbstractMesh));
  60424. BABYLON.InstancedMesh = InstancedMesh;
  60425. })(BABYLON || (BABYLON = {}));
  60426. //# sourceMappingURL=babylon.instancedMesh.js.map
  60427. var BABYLON;
  60428. (function (BABYLON) {
  60429. var LinesMesh = /** @class */ (function (_super) {
  60430. __extends(LinesMesh, _super);
  60431. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60432. if (scene === void 0) { scene = null; }
  60433. if (parent === void 0) { parent = null; }
  60434. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60435. _this.useVertexColor = useVertexColor;
  60436. _this.useVertexAlpha = useVertexAlpha;
  60437. _this.color = new BABYLON.Color3(1, 1, 1);
  60438. _this.alpha = 1;
  60439. if (source) {
  60440. _this.color = source.color.clone();
  60441. _this.alpha = source.alpha;
  60442. _this.useVertexColor = source.useVertexColor;
  60443. _this.useVertexAlpha = source.useVertexAlpha;
  60444. }
  60445. _this._intersectionThreshold = 0.1;
  60446. var defines = [];
  60447. var options = {
  60448. attributes: [BABYLON.VertexBuffer.PositionKind],
  60449. uniforms: ["world", "viewProjection"],
  60450. needAlphaBlending: true,
  60451. defines: defines
  60452. };
  60453. if (useVertexAlpha === false) {
  60454. options.needAlphaBlending = false;
  60455. }
  60456. if (!useVertexColor) {
  60457. options.uniforms.push("color");
  60458. }
  60459. else {
  60460. options.defines.push("#define VERTEXCOLOR");
  60461. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60462. }
  60463. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60464. return _this;
  60465. }
  60466. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60467. /**
  60468. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60469. * This margin is expressed in world space coordinates, so its value may vary.
  60470. * Default value is 0.1
  60471. * @returns the intersection Threshold value.
  60472. */
  60473. get: function () {
  60474. return this._intersectionThreshold;
  60475. },
  60476. /**
  60477. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60478. * This margin is expressed in world space coordinates, so its value may vary.
  60479. * @param value the new threshold to apply
  60480. */
  60481. set: function (value) {
  60482. if (this._intersectionThreshold === value) {
  60483. return;
  60484. }
  60485. this._intersectionThreshold = value;
  60486. if (this.geometry) {
  60487. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60488. }
  60489. },
  60490. enumerable: true,
  60491. configurable: true
  60492. });
  60493. /**
  60494. * Returns the string "LineMesh"
  60495. */
  60496. LinesMesh.prototype.getClassName = function () {
  60497. return "LinesMesh";
  60498. };
  60499. Object.defineProperty(LinesMesh.prototype, "material", {
  60500. get: function () {
  60501. return this._colorShader;
  60502. },
  60503. set: function (value) {
  60504. // Do nothing
  60505. },
  60506. enumerable: true,
  60507. configurable: true
  60508. });
  60509. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60510. get: function () {
  60511. return false;
  60512. },
  60513. enumerable: true,
  60514. configurable: true
  60515. });
  60516. LinesMesh.prototype.createInstance = function (name) {
  60517. throw new Error("LinesMeshes do not support createInstance.");
  60518. };
  60519. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60520. if (!this._geometry) {
  60521. return this;
  60522. }
  60523. // VBOs
  60524. this._geometry._bind(this._colorShader.getEffect());
  60525. // Color
  60526. if (!this.useVertexColor) {
  60527. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60528. }
  60529. return this;
  60530. };
  60531. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60532. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60533. return this;
  60534. }
  60535. var engine = this.getScene().getEngine();
  60536. // Draw order
  60537. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60538. return this;
  60539. };
  60540. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60541. this._colorShader.dispose();
  60542. _super.prototype.dispose.call(this, doNotRecurse);
  60543. };
  60544. /**
  60545. * Returns a new LineMesh object cloned from the current one.
  60546. */
  60547. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60548. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60549. };
  60550. return LinesMesh;
  60551. }(BABYLON.Mesh));
  60552. BABYLON.LinesMesh = LinesMesh;
  60553. })(BABYLON || (BABYLON = {}));
  60554. //# sourceMappingURL=babylon.linesMesh.js.map
  60555. var BABYLON;
  60556. (function (BABYLON) {
  60557. /**
  60558. * Class containing static functions to help procedurally build meshes
  60559. */
  60560. var MeshBuilder = /** @class */ (function () {
  60561. function MeshBuilder() {
  60562. }
  60563. MeshBuilder.updateSideOrientation = function (orientation) {
  60564. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60565. return BABYLON.Mesh.DOUBLESIDE;
  60566. }
  60567. if (orientation === undefined || orientation === null) {
  60568. return BABYLON.Mesh.FRONTSIDE;
  60569. }
  60570. return orientation;
  60571. };
  60572. /**
  60573. * Creates a box mesh
  60574. * * The parameter `size` sets the size (float) of each box side (default 1)
  60575. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60576. * * 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)
  60577. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60578. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60579. * * 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
  60580. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60581. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60582. * @param name defines the name of the mesh
  60583. * @param options defines the options used to create the mesh
  60584. * @param scene defines the hosting scene
  60585. * @returns the box mesh
  60586. */
  60587. MeshBuilder.CreateBox = function (name, options, scene) {
  60588. if (scene === void 0) { scene = null; }
  60589. var box = new BABYLON.Mesh(name, scene);
  60590. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60591. box._originalBuilderSideOrientation = options.sideOrientation;
  60592. var vertexData = BABYLON.VertexData.CreateBox(options);
  60593. vertexData.applyToMesh(box, options.updatable);
  60594. return box;
  60595. };
  60596. /**
  60597. * Creates a sphere mesh
  60598. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60599. * * 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`)
  60600. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60601. * * 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
  60602. * * 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)
  60603. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60604. * * 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
  60605. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60606. * @param name defines the name of the mesh
  60607. * @param options defines the options used to create the mesh
  60608. * @param scene defines the hosting scene
  60609. * @returns the sphere mesh
  60610. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60611. */
  60612. MeshBuilder.CreateSphere = function (name, options, scene) {
  60613. var sphere = new BABYLON.Mesh(name, scene);
  60614. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60615. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60616. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60617. vertexData.applyToMesh(sphere, options.updatable);
  60618. return sphere;
  60619. };
  60620. /**
  60621. * Creates a plane polygonal mesh. By default, this is a disc
  60622. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60623. * * 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
  60624. * * 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
  60625. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60626. * * 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
  60627. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60628. * @param name defines the name of the mesh
  60629. * @param options defines the options used to create the mesh
  60630. * @param scene defines the hosting scene
  60631. * @returns the plane polygonal mesh
  60632. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60633. */
  60634. MeshBuilder.CreateDisc = function (name, options, scene) {
  60635. if (scene === void 0) { scene = null; }
  60636. var disc = new BABYLON.Mesh(name, scene);
  60637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60638. disc._originalBuilderSideOrientation = options.sideOrientation;
  60639. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60640. vertexData.applyToMesh(disc, options.updatable);
  60641. return disc;
  60642. };
  60643. /**
  60644. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60645. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60646. * * 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`)
  60647. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60648. * * 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
  60649. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60650. * * 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
  60651. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60652. * @param name defines the name of the mesh
  60653. * @param options defines the options used to create the mesh
  60654. * @param scene defines the hosting scene
  60655. * @returns the icosahedron mesh
  60656. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60657. */
  60658. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60659. var sphere = new BABYLON.Mesh(name, scene);
  60660. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60661. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60662. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60663. vertexData.applyToMesh(sphere, options.updatable);
  60664. return sphere;
  60665. };
  60666. ;
  60667. /**
  60668. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60669. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60670. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60671. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60672. * * 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
  60673. * * 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
  60674. * * 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
  60675. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60676. * * 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
  60677. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60678. * * 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
  60679. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60680. * * 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
  60681. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60682. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60683. * @param name defines the name of the mesh
  60684. * @param options defines the options used to create the mesh
  60685. * @param scene defines the hosting scene
  60686. * @returns the ribbon mesh
  60687. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60688. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60689. */
  60690. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60691. if (scene === void 0) { scene = null; }
  60692. var pathArray = options.pathArray;
  60693. var closeArray = options.closeArray;
  60694. var closePath = options.closePath;
  60695. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60696. var instance = options.instance;
  60697. var updatable = options.updatable;
  60698. if (instance) { // existing ribbon instance update
  60699. // positionFunction : ribbon case
  60700. // only pathArray and sideOrientation parameters are taken into account for positions update
  60701. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60702. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60703. var positionFunction = function (positions) {
  60704. var minlg = pathArray[0].length;
  60705. var i = 0;
  60706. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60707. for (var si = 1; si <= ns; si++) {
  60708. for (var p = 0; p < pathArray.length; p++) {
  60709. var path = pathArray[p];
  60710. var l = path.length;
  60711. minlg = (minlg < l) ? minlg : l;
  60712. var j = 0;
  60713. while (j < minlg) {
  60714. positions[i] = path[j].x;
  60715. positions[i + 1] = path[j].y;
  60716. positions[i + 2] = path[j].z;
  60717. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60718. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60719. }
  60720. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60721. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60722. }
  60723. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60724. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60725. }
  60726. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60727. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60728. }
  60729. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60730. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60731. }
  60732. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60733. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60734. }
  60735. j++;
  60736. i += 3;
  60737. }
  60738. if (instance._closePath) {
  60739. positions[i] = path[0].x;
  60740. positions[i + 1] = path[0].y;
  60741. positions[i + 2] = path[0].z;
  60742. i += 3;
  60743. }
  60744. }
  60745. }
  60746. };
  60747. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60748. positionFunction(positions);
  60749. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60750. instance._boundingInfo.update(instance._worldMatrix);
  60751. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60752. if (options.colors) {
  60753. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60754. for (var c = 0; c < options.colors.length; c++) {
  60755. colors[c * 4] = options.colors[c].r;
  60756. colors[c * 4 + 1] = options.colors[c].g;
  60757. colors[c * 4 + 2] = options.colors[c].b;
  60758. colors[c * 4 + 3] = options.colors[c].a;
  60759. }
  60760. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60761. }
  60762. if (options.uvs) {
  60763. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60764. for (var i = 0; i < options.uvs.length; i++) {
  60765. uvs[i * 2] = options.uvs[i].x;
  60766. uvs[i * 2 + 1] = options.uvs[i].y;
  60767. }
  60768. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60769. }
  60770. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60771. var indices = instance.getIndices();
  60772. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60773. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60774. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60775. if (instance._closePath) {
  60776. var indexFirst = 0;
  60777. var indexLast = 0;
  60778. for (var p = 0; p < pathArray.length; p++) {
  60779. indexFirst = instance._idx[p] * 3;
  60780. if (p + 1 < pathArray.length) {
  60781. indexLast = (instance._idx[p + 1] - 1) * 3;
  60782. }
  60783. else {
  60784. indexLast = normals.length - 3;
  60785. }
  60786. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60787. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60788. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60789. normals[indexLast] = normals[indexFirst];
  60790. normals[indexLast + 1] = normals[indexFirst + 1];
  60791. normals[indexLast + 2] = normals[indexFirst + 2];
  60792. }
  60793. }
  60794. if (!(instance.areNormalsFrozen)) {
  60795. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60796. }
  60797. }
  60798. return instance;
  60799. }
  60800. else { // new ribbon creation
  60801. var ribbon = new BABYLON.Mesh(name, scene);
  60802. ribbon._originalBuilderSideOrientation = sideOrientation;
  60803. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60804. if (closePath) {
  60805. ribbon._idx = vertexData._idx;
  60806. }
  60807. ribbon._closePath = closePath;
  60808. ribbon._closeArray = closeArray;
  60809. vertexData.applyToMesh(ribbon, updatable);
  60810. return ribbon;
  60811. }
  60812. };
  60813. /**
  60814. * Creates a cylinder or a cone mesh
  60815. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60816. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60817. * * 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.
  60818. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60819. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60820. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60821. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60822. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60823. * * 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).
  60824. * * 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
  60825. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60826. * * 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
  60827. * * 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.
  60828. * * If `enclose` is false, a ring surface is one element.
  60829. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60830. * * 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
  60831. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60832. * * 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
  60833. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60834. * @param name defines the name of the mesh
  60835. * @param options defines the options used to create the mesh
  60836. * @param scene defines the hosting scene
  60837. * @returns the cylinder mesh
  60838. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60839. */
  60840. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60841. var cylinder = new BABYLON.Mesh(name, scene);
  60842. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60843. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60844. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60845. vertexData.applyToMesh(cylinder, options.updatable);
  60846. return cylinder;
  60847. };
  60848. /**
  60849. * Creates a torus mesh
  60850. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60851. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60852. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60853. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60854. * * 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
  60855. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60856. * @param name defines the name of the mesh
  60857. * @param options defines the options used to create the mesh
  60858. * @param scene defines the hosting scene
  60859. * @returns the torus mesh
  60860. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60861. */
  60862. MeshBuilder.CreateTorus = function (name, options, scene) {
  60863. var torus = new BABYLON.Mesh(name, scene);
  60864. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60865. torus._originalBuilderSideOrientation = options.sideOrientation;
  60866. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60867. vertexData.applyToMesh(torus, options.updatable);
  60868. return torus;
  60869. };
  60870. /**
  60871. * Creates a torus knot mesh
  60872. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60873. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60874. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60875. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60876. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60877. * * 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
  60878. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60879. * @param name defines the name of the mesh
  60880. * @param options defines the options used to create the mesh
  60881. * @param scene defines the hosting scene
  60882. * @returns the torus knot mesh
  60883. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60884. */
  60885. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60886. var torusKnot = new BABYLON.Mesh(name, scene);
  60887. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60888. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60889. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60890. vertexData.applyToMesh(torusKnot, options.updatable);
  60891. return torusKnot;
  60892. };
  60893. /**
  60894. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60895. * * 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
  60896. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60897. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60898. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60899. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60900. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60901. * * 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
  60902. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60903. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60904. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60905. * @param name defines the name of the new line system
  60906. * @param options defines the options used to create the line system
  60907. * @param scene defines the hosting scene
  60908. * @returns a new line system mesh
  60909. */
  60910. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60911. var instance = options.instance;
  60912. var lines = options.lines;
  60913. var colors = options.colors;
  60914. if (instance) { // lines update
  60915. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60916. var vertexColor;
  60917. var lineColors;
  60918. if (colors) {
  60919. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60920. }
  60921. var i = 0;
  60922. var c = 0;
  60923. for (var l = 0; l < lines.length; l++) {
  60924. var points = lines[l];
  60925. for (var p = 0; p < points.length; p++) {
  60926. positions[i] = points[p].x;
  60927. positions[i + 1] = points[p].y;
  60928. positions[i + 2] = points[p].z;
  60929. if (colors && vertexColor) {
  60930. lineColors = colors[l];
  60931. vertexColor[c] = lineColors[p].r;
  60932. vertexColor[c + 1] = lineColors[p].g;
  60933. vertexColor[c + 2] = lineColors[p].b;
  60934. vertexColor[c + 3] = lineColors[p].a;
  60935. c += 4;
  60936. }
  60937. i += 3;
  60938. }
  60939. }
  60940. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60941. if (colors && vertexColor) {
  60942. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60943. }
  60944. return instance;
  60945. }
  60946. // line system creation
  60947. var useVertexColor = (colors) ? true : false;
  60948. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60949. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60950. vertexData.applyToMesh(lineSystem, options.updatable);
  60951. return lineSystem;
  60952. };
  60953. /**
  60954. * Creates a line mesh
  60955. * 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
  60956. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60957. * * The parameter `points` is an array successive Vector3
  60958. * * 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
  60959. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60960. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60961. * * When updating an instance, remember that only point positions can change, not the number of points
  60962. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60963. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60964. * @param name defines the name of the new line system
  60965. * @param options defines the options used to create the line system
  60966. * @param scene defines the hosting scene
  60967. * @returns a new line mesh
  60968. */
  60969. MeshBuilder.CreateLines = function (name, options, scene) {
  60970. if (scene === void 0) { scene = null; }
  60971. var colors = (options.colors) ? [options.colors] : null;
  60972. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60973. return lines;
  60974. };
  60975. /**
  60976. * Creates a dashed line mesh
  60977. * * 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
  60978. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60979. * * The parameter `points` is an array successive Vector3
  60980. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60981. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60982. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60983. * * 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
  60984. * * When updating an instance, remember that only point positions can change, not the number of points
  60985. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60986. * @param name defines the name of the mesh
  60987. * @param options defines the options used to create the mesh
  60988. * @param scene defines the hosting scene
  60989. * @returns the dashed line mesh
  60990. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60991. */
  60992. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60993. if (scene === void 0) { scene = null; }
  60994. var points = options.points;
  60995. var instance = options.instance;
  60996. var gapSize = options.gapSize || 1;
  60997. var dashSize = options.dashSize || 3;
  60998. if (instance) { // dashed lines update
  60999. var positionFunction = function (positions) {
  61000. var curvect = BABYLON.Vector3.Zero();
  61001. var nbSeg = positions.length / 6;
  61002. var lg = 0;
  61003. var nb = 0;
  61004. var shft = 0;
  61005. var dashshft = 0;
  61006. var curshft = 0;
  61007. var p = 0;
  61008. var i = 0;
  61009. var j = 0;
  61010. for (i = 0; i < points.length - 1; i++) {
  61011. points[i + 1].subtractToRef(points[i], curvect);
  61012. lg += curvect.length();
  61013. }
  61014. shft = lg / nbSeg;
  61015. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61016. for (i = 0; i < points.length - 1; i++) {
  61017. points[i + 1].subtractToRef(points[i], curvect);
  61018. nb = Math.floor(curvect.length() / shft);
  61019. curvect.normalize();
  61020. j = 0;
  61021. while (j < nb && p < positions.length) {
  61022. curshft = shft * j;
  61023. positions[p] = points[i].x + curshft * curvect.x;
  61024. positions[p + 1] = points[i].y + curshft * curvect.y;
  61025. positions[p + 2] = points[i].z + curshft * curvect.z;
  61026. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61027. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61028. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61029. p += 6;
  61030. j++;
  61031. }
  61032. }
  61033. while (p < positions.length) {
  61034. positions[p] = points[i].x;
  61035. positions[p + 1] = points[i].y;
  61036. positions[p + 2] = points[i].z;
  61037. p += 3;
  61038. }
  61039. };
  61040. instance.updateMeshPositions(positionFunction, false);
  61041. return instance;
  61042. }
  61043. // dashed lines creation
  61044. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61045. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61046. vertexData.applyToMesh(dashedLines, options.updatable);
  61047. dashedLines.dashSize = dashSize;
  61048. dashedLines.gapSize = gapSize;
  61049. return dashedLines;
  61050. };
  61051. /**
  61052. * 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.
  61053. * * 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.
  61054. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61055. * * 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.
  61056. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61057. * * 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
  61058. * * 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
  61059. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61060. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61061. * * 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
  61062. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61064. * @param name defines the name of the mesh
  61065. * @param options defines the options used to create the mesh
  61066. * @param scene defines the hosting scene
  61067. * @returns the extruded shape mesh
  61068. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61069. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61070. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61071. */
  61072. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61073. if (scene === void 0) { scene = null; }
  61074. var path = options.path;
  61075. var shape = options.shape;
  61076. var scale = options.scale || 1;
  61077. var rotation = options.rotation || 0;
  61078. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61079. var updatable = options.updatable;
  61080. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61081. var instance = options.instance || null;
  61082. var invertUV = options.invertUV || false;
  61083. 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);
  61084. };
  61085. /**
  61086. * Creates an custom extruded shape mesh.
  61087. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61088. * * 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.
  61089. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61090. * * 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
  61091. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61092. * * 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
  61093. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61094. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61095. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61096. * * 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
  61097. * * 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
  61098. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61099. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61100. * * 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
  61101. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61102. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61103. * @param name defines the name of the mesh
  61104. * @param options defines the options used to create the mesh
  61105. * @param scene defines the hosting scene
  61106. * @returns the custom extruded shape mesh
  61107. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61108. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61109. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61110. */
  61111. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61112. var path = options.path;
  61113. var shape = options.shape;
  61114. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61115. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61116. var ribbonCloseArray = options.ribbonCloseArray || false;
  61117. var ribbonClosePath = options.ribbonClosePath || false;
  61118. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61119. var updatable = options.updatable;
  61120. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61121. var instance = options.instance;
  61122. var invertUV = options.invertUV || false;
  61123. 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);
  61124. };
  61125. /**
  61126. * Creates lathe mesh.
  61127. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61128. * * 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
  61129. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61130. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61131. * * 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
  61132. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61133. * * 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
  61134. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61135. * * 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
  61136. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61137. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61138. * @param name defines the name of the mesh
  61139. * @param options defines the options used to create the mesh
  61140. * @param scene defines the hosting scene
  61141. * @returns the lathe mesh
  61142. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61143. */
  61144. MeshBuilder.CreateLathe = function (name, options, scene) {
  61145. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61146. var closed = (options.closed === undefined) ? true : options.closed;
  61147. var shape = options.shape;
  61148. var radius = options.radius || 1;
  61149. var tessellation = options.tessellation || 64;
  61150. var updatable = options.updatable;
  61151. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61152. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61153. var pi2 = Math.PI * 2;
  61154. var paths = new Array();
  61155. var invertUV = options.invertUV || false;
  61156. var i = 0;
  61157. var p = 0;
  61158. var step = pi2 / tessellation * arc;
  61159. var rotated;
  61160. var path = new Array();
  61161. for (i = 0; i <= tessellation; i++) {
  61162. var path = [];
  61163. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61164. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61165. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61166. }
  61167. for (p = 0; p < shape.length; p++) {
  61168. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61169. path.push(rotated);
  61170. }
  61171. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61172. 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));
  61173. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61174. }
  61175. paths.push(path);
  61176. }
  61177. // lathe ribbon
  61178. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61179. return lathe;
  61180. };
  61181. /**
  61182. * Creates a plane mesh
  61183. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61184. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61185. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61186. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61187. * * 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
  61188. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61189. * @param name defines the name of the mesh
  61190. * @param options defines the options used to create the mesh
  61191. * @param scene defines the hosting scene
  61192. * @returns the plane mesh
  61193. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61194. */
  61195. MeshBuilder.CreatePlane = function (name, options, scene) {
  61196. var plane = new BABYLON.Mesh(name, scene);
  61197. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61198. plane._originalBuilderSideOrientation = options.sideOrientation;
  61199. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61200. vertexData.applyToMesh(plane, options.updatable);
  61201. if (options.sourcePlane) {
  61202. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61203. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61204. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61205. plane.rotate(vectorProduct, product);
  61206. }
  61207. return plane;
  61208. };
  61209. /**
  61210. * Creates a ground mesh
  61211. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61212. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61213. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61214. * @param name defines the name of the mesh
  61215. * @param options defines the options used to create the mesh
  61216. * @param scene defines the hosting scene
  61217. * @returns the ground mesh
  61218. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61219. */
  61220. MeshBuilder.CreateGround = function (name, options, scene) {
  61221. var ground = new BABYLON.GroundMesh(name, scene);
  61222. ground._setReady(false);
  61223. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61224. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61225. ground._width = options.width || 1;
  61226. ground._height = options.height || 1;
  61227. ground._maxX = ground._width / 2;
  61228. ground._maxZ = ground._height / 2;
  61229. ground._minX = -ground._maxX;
  61230. ground._minZ = -ground._maxZ;
  61231. var vertexData = BABYLON.VertexData.CreateGround(options);
  61232. vertexData.applyToMesh(ground, options.updatable);
  61233. ground._setReady(true);
  61234. return ground;
  61235. };
  61236. /**
  61237. * Creates a tiled ground mesh
  61238. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61239. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61240. * * 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
  61241. * * 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
  61242. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61243. * @param name defines the name of the mesh
  61244. * @param options defines the options used to create the mesh
  61245. * @param scene defines the hosting scene
  61246. * @returns the tiled ground mesh
  61247. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61248. */
  61249. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61250. var tiledGround = new BABYLON.Mesh(name, scene);
  61251. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61252. vertexData.applyToMesh(tiledGround, options.updatable);
  61253. return tiledGround;
  61254. };
  61255. /**
  61256. * Creates a ground mesh from a height map
  61257. * * The parameter `url` sets the URL of the height map image resource.
  61258. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61259. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61260. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61261. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61262. * * 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.
  61263. * * 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).
  61264. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61265. * @param name defines the name of the mesh
  61266. * @param url defines the url to the height map
  61267. * @param options defines the options used to create the mesh
  61268. * @param scene defines the hosting scene
  61269. * @returns the ground mesh
  61270. * @see http://doc.babylonjs.com/babylon101/height_map
  61271. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61272. */
  61273. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61274. var width = options.width || 10.0;
  61275. var height = options.height || 10.0;
  61276. var subdivisions = options.subdivisions || 1 | 0;
  61277. var minHeight = options.minHeight || 0.0;
  61278. var maxHeight = options.maxHeight || 1.0;
  61279. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61280. var updatable = options.updatable;
  61281. var onReady = options.onReady;
  61282. var ground = new BABYLON.GroundMesh(name, scene);
  61283. ground._subdivisionsX = subdivisions;
  61284. ground._subdivisionsY = subdivisions;
  61285. ground._width = width;
  61286. ground._height = height;
  61287. ground._maxX = ground._width / 2.0;
  61288. ground._maxZ = ground._height / 2.0;
  61289. ground._minX = -ground._maxX;
  61290. ground._minZ = -ground._maxZ;
  61291. ground._setReady(false);
  61292. var onload = function (img) {
  61293. // Getting height map data
  61294. var canvas = document.createElement("canvas");
  61295. var context = canvas.getContext("2d");
  61296. if (!context) {
  61297. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61298. }
  61299. if (scene.isDisposed) {
  61300. return;
  61301. }
  61302. var bufferWidth = img.width;
  61303. var bufferHeight = img.height;
  61304. canvas.width = bufferWidth;
  61305. canvas.height = bufferHeight;
  61306. context.drawImage(img, 0, 0);
  61307. // Create VertexData from map data
  61308. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61309. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61310. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61311. width: width, height: height,
  61312. subdivisions: subdivisions,
  61313. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61314. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61315. });
  61316. vertexData.applyToMesh(ground, updatable);
  61317. //execute ready callback, if set
  61318. if (onReady) {
  61319. onReady(ground);
  61320. }
  61321. ground._setReady(true);
  61322. };
  61323. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61324. return ground;
  61325. };
  61326. /**
  61327. * Creates a polygon mesh
  61328. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61329. * * 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
  61330. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61332. * * 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)
  61333. * * Remember you can only change the shape positions, not their number when updating a polygon
  61334. * @param name defines the name of the mesh
  61335. * @param options defines the options used to create the mesh
  61336. * @param scene defines the hosting scene
  61337. * @returns the polygon mesh
  61338. */
  61339. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61341. var shape = options.shape;
  61342. var holes = options.holes || [];
  61343. var depth = options.depth || 0;
  61344. var contours = [];
  61345. var hole = [];
  61346. for (var i = 0; i < shape.length; i++) {
  61347. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61348. }
  61349. var epsilon = 0.00000001;
  61350. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61351. contours.pop();
  61352. }
  61353. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61354. for (var hNb = 0; hNb < holes.length; hNb++) {
  61355. hole = [];
  61356. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61357. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61358. }
  61359. polygonTriangulation.addHole(hole);
  61360. }
  61361. var polygon = polygonTriangulation.build(options.updatable, depth);
  61362. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61363. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61364. vertexData.applyToMesh(polygon, options.updatable);
  61365. return polygon;
  61366. };
  61367. ;
  61368. /**
  61369. * Creates an extruded polygon mesh, with depth in the Y direction.
  61370. * * 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)
  61371. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61372. * @param name defines the name of the mesh
  61373. * @param options defines the options used to create the mesh
  61374. * @param scene defines the hosting scene
  61375. * @returns the polygon mesh
  61376. */
  61377. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61378. return MeshBuilder.CreatePolygon(name, options, scene);
  61379. };
  61380. ;
  61381. /**
  61382. * Creates a tube mesh.
  61383. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61384. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61385. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61386. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61387. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61388. * * 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)
  61389. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61390. * * 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
  61391. * * 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
  61392. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61393. * * 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
  61394. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61395. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61396. * @param name defines the name of the mesh
  61397. * @param options defines the options used to create the mesh
  61398. * @param scene defines the hosting scene
  61399. * @returns the tube mesh
  61400. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61401. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61402. */
  61403. MeshBuilder.CreateTube = function (name, options, scene) {
  61404. var path = options.path;
  61405. var instance = options.instance;
  61406. var radius = 1.0;
  61407. if (instance) {
  61408. radius = instance.radius;
  61409. }
  61410. if (options.radius !== undefined) {
  61411. radius = options.radius;
  61412. }
  61413. ;
  61414. var tessellation = options.tessellation || 64 | 0;
  61415. var radiusFunction = options.radiusFunction || null;
  61416. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61417. var invertUV = options.invertUV || false;
  61418. var updatable = options.updatable;
  61419. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61420. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61421. // tube geometry
  61422. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61423. var tangents = path3D.getTangents();
  61424. var normals = path3D.getNormals();
  61425. var distances = path3D.getDistances();
  61426. var pi2 = Math.PI * 2;
  61427. var step = pi2 / tessellation * arc;
  61428. var returnRadius = function () { return radius; };
  61429. var radiusFunctionFinal = radiusFunction || returnRadius;
  61430. var circlePath;
  61431. var rad;
  61432. var normal;
  61433. var rotated;
  61434. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61435. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61436. for (var i = 0; i < path.length; i++) {
  61437. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61438. circlePath = Array(); // current circle array
  61439. normal = normals[i]; // current normal
  61440. for (var t = 0; t < tessellation; t++) {
  61441. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61442. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61443. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61444. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61445. circlePath[t] = rotated;
  61446. }
  61447. circlePaths[index] = circlePath;
  61448. index++;
  61449. }
  61450. // cap
  61451. var capPath = function (nbPoints, pathIndex) {
  61452. var pointCap = Array();
  61453. for (var i = 0; i < nbPoints; i++) {
  61454. pointCap.push(path[pathIndex]);
  61455. }
  61456. return pointCap;
  61457. };
  61458. switch (cap) {
  61459. case BABYLON.Mesh.NO_CAP:
  61460. break;
  61461. case BABYLON.Mesh.CAP_START:
  61462. circlePaths[0] = capPath(tessellation, 0);
  61463. circlePaths[1] = circlePaths[2].slice(0);
  61464. break;
  61465. case BABYLON.Mesh.CAP_END:
  61466. circlePaths[index] = circlePaths[index - 1].slice(0);
  61467. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61468. break;
  61469. case BABYLON.Mesh.CAP_ALL:
  61470. circlePaths[0] = capPath(tessellation, 0);
  61471. circlePaths[1] = circlePaths[2].slice(0);
  61472. circlePaths[index] = circlePaths[index - 1].slice(0);
  61473. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61474. break;
  61475. default:
  61476. break;
  61477. }
  61478. return circlePaths;
  61479. };
  61480. var path3D;
  61481. var pathArray;
  61482. if (instance) { // tube update
  61483. var arc = options.arc || instance.arc;
  61484. path3D = (instance.path3D).update(path);
  61485. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61486. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61487. instance.path3D = path3D;
  61488. instance.pathArray = pathArray;
  61489. instance.arc = arc;
  61490. instance.radius = radius;
  61491. return instance;
  61492. }
  61493. // tube creation
  61494. path3D = new BABYLON.Path3D(path);
  61495. var newPathArray = new Array();
  61496. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61497. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61498. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61499. tube.pathArray = pathArray;
  61500. tube.path3D = path3D;
  61501. tube.tessellation = tessellation;
  61502. tube.cap = cap;
  61503. tube.arc = options.arc;
  61504. tube.radius = radius;
  61505. return tube;
  61506. };
  61507. /**
  61508. * Creates a polyhedron mesh
  61509. * * 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
  61510. * * The parameter `size` (positive float, default 1) sets the polygon size
  61511. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61512. * * 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`
  61513. * * 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
  61514. * * 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)`)
  61515. * * 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
  61516. * * 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
  61517. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61518. * * 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
  61519. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61520. * @param name defines the name of the mesh
  61521. * @param options defines the options used to create the mesh
  61522. * @param scene defines the hosting scene
  61523. * @returns the polyhedron mesh
  61524. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61525. */
  61526. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61527. var polyhedron = new BABYLON.Mesh(name, scene);
  61528. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61529. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61530. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61531. vertexData.applyToMesh(polyhedron, options.updatable);
  61532. return polyhedron;
  61533. };
  61534. /**
  61535. * Creates a decal mesh.
  61536. * 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
  61537. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61538. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61539. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61540. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61541. * @param name defines the name of the mesh
  61542. * @param sourceMesh defines the mesh where the decal must be applied
  61543. * @param options defines the options used to create the mesh
  61544. * @param scene defines the hosting scene
  61545. * @returns the decal mesh
  61546. * @see http://doc.babylonjs.com/how_to/decals
  61547. */
  61548. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61549. var indices = sourceMesh.getIndices();
  61550. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61551. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61552. var position = options.position || BABYLON.Vector3.Zero();
  61553. var normal = options.normal || BABYLON.Vector3.Up();
  61554. var size = options.size || BABYLON.Vector3.One();
  61555. var angle = options.angle || 0;
  61556. // Getting correct rotation
  61557. if (!normal) {
  61558. var target = new BABYLON.Vector3(0, 0, 1);
  61559. var camera = sourceMesh.getScene().activeCamera;
  61560. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61561. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61562. }
  61563. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61564. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61565. var pitch = Math.atan2(normal.y, len);
  61566. // Matrix
  61567. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61568. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61569. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61570. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61571. var vertexData = new BABYLON.VertexData();
  61572. vertexData.indices = [];
  61573. vertexData.positions = [];
  61574. vertexData.normals = [];
  61575. vertexData.uvs = [];
  61576. var currentVertexDataIndex = 0;
  61577. var extractDecalVector3 = function (indexId) {
  61578. var result = new BABYLON.PositionNormalVertex();
  61579. if (!indices || !positions || !normals) {
  61580. return result;
  61581. }
  61582. var vertexId = indices[indexId];
  61583. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61584. // Send vector to decal local world
  61585. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61586. // Get normal
  61587. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61588. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61589. return result;
  61590. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61591. var clip = function (vertices, axis) {
  61592. if (vertices.length === 0) {
  61593. return vertices;
  61594. }
  61595. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61596. var clipVertices = function (v0, v1) {
  61597. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61598. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61599. };
  61600. var result = new Array();
  61601. for (var index = 0; index < vertices.length; index += 3) {
  61602. var v1Out;
  61603. var v2Out;
  61604. var v3Out;
  61605. var total = 0;
  61606. var nV1 = null;
  61607. var nV2 = null;
  61608. var nV3 = null;
  61609. var nV4 = null;
  61610. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61611. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61612. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61613. v1Out = d1 > 0;
  61614. v2Out = d2 > 0;
  61615. v3Out = d3 > 0;
  61616. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61617. switch (total) {
  61618. case 0:
  61619. result.push(vertices[index]);
  61620. result.push(vertices[index + 1]);
  61621. result.push(vertices[index + 2]);
  61622. break;
  61623. case 1:
  61624. if (v1Out) {
  61625. nV1 = vertices[index + 1];
  61626. nV2 = vertices[index + 2];
  61627. nV3 = clipVertices(vertices[index], nV1);
  61628. nV4 = clipVertices(vertices[index], nV2);
  61629. }
  61630. if (v2Out) {
  61631. nV1 = vertices[index];
  61632. nV2 = vertices[index + 2];
  61633. nV3 = clipVertices(vertices[index + 1], nV1);
  61634. nV4 = clipVertices(vertices[index + 1], nV2);
  61635. result.push(nV3);
  61636. result.push(nV2.clone());
  61637. result.push(nV1.clone());
  61638. result.push(nV2.clone());
  61639. result.push(nV3.clone());
  61640. result.push(nV4);
  61641. break;
  61642. }
  61643. if (v3Out) {
  61644. nV1 = vertices[index];
  61645. nV2 = vertices[index + 1];
  61646. nV3 = clipVertices(vertices[index + 2], nV1);
  61647. nV4 = clipVertices(vertices[index + 2], nV2);
  61648. }
  61649. if (nV1 && nV2 && nV3 && nV4) {
  61650. result.push(nV1.clone());
  61651. result.push(nV2.clone());
  61652. result.push(nV3);
  61653. result.push(nV4);
  61654. result.push(nV3.clone());
  61655. result.push(nV2.clone());
  61656. }
  61657. break;
  61658. case 2:
  61659. if (!v1Out) {
  61660. nV1 = vertices[index].clone();
  61661. nV2 = clipVertices(nV1, vertices[index + 1]);
  61662. nV3 = clipVertices(nV1, vertices[index + 2]);
  61663. result.push(nV1);
  61664. result.push(nV2);
  61665. result.push(nV3);
  61666. }
  61667. if (!v2Out) {
  61668. nV1 = vertices[index + 1].clone();
  61669. nV2 = clipVertices(nV1, vertices[index + 2]);
  61670. nV3 = clipVertices(nV1, vertices[index]);
  61671. result.push(nV1);
  61672. result.push(nV2);
  61673. result.push(nV3);
  61674. }
  61675. if (!v3Out) {
  61676. nV1 = vertices[index + 2].clone();
  61677. nV2 = clipVertices(nV1, vertices[index]);
  61678. nV3 = clipVertices(nV1, vertices[index + 1]);
  61679. result.push(nV1);
  61680. result.push(nV2);
  61681. result.push(nV3);
  61682. }
  61683. break;
  61684. case 3:
  61685. break;
  61686. }
  61687. }
  61688. return result;
  61689. };
  61690. for (var index = 0; index < indices.length; index += 3) {
  61691. var faceVertices = new Array();
  61692. faceVertices.push(extractDecalVector3(index));
  61693. faceVertices.push(extractDecalVector3(index + 1));
  61694. faceVertices.push(extractDecalVector3(index + 2));
  61695. // Clip
  61696. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61697. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61698. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61699. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61700. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61701. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61702. if (faceVertices.length === 0) {
  61703. continue;
  61704. }
  61705. // Add UVs and get back to world
  61706. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61707. var vertex = faceVertices[vIndex];
  61708. //TODO check for Int32Array | Uint32Array | Uint16Array
  61709. vertexData.indices.push(currentVertexDataIndex);
  61710. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61711. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61712. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61713. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61714. currentVertexDataIndex++;
  61715. }
  61716. }
  61717. // Return mesh
  61718. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61719. vertexData.applyToMesh(decal);
  61720. decal.position = position.clone();
  61721. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61722. return decal;
  61723. };
  61724. // Privates
  61725. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61726. // extrusion geometry
  61727. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61728. var tangents = path3D.getTangents();
  61729. var normals = path3D.getNormals();
  61730. var binormals = path3D.getBinormals();
  61731. var distances = path3D.getDistances();
  61732. var angle = 0;
  61733. var returnScale = function () { return scale !== null ? scale : 1; };
  61734. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61735. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61736. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61737. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61738. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61739. for (var i = 0; i < curve.length; i++) {
  61740. var shapePath = new Array();
  61741. var angleStep = rotate(i, distances[i]);
  61742. var scaleRatio = scl(i, distances[i]);
  61743. for (var p = 0; p < shape.length; p++) {
  61744. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61745. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61746. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61747. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61748. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61749. shapePath[p] = rotated;
  61750. }
  61751. shapePaths[index] = shapePath;
  61752. angle += angleStep;
  61753. index++;
  61754. }
  61755. // cap
  61756. var capPath = function (shapePath) {
  61757. var pointCap = Array();
  61758. var barycenter = BABYLON.Vector3.Zero();
  61759. var i;
  61760. for (i = 0; i < shapePath.length; i++) {
  61761. barycenter.addInPlace(shapePath[i]);
  61762. }
  61763. barycenter.scaleInPlace(1.0 / shapePath.length);
  61764. for (i = 0; i < shapePath.length; i++) {
  61765. pointCap.push(barycenter);
  61766. }
  61767. return pointCap;
  61768. };
  61769. switch (cap) {
  61770. case BABYLON.Mesh.NO_CAP:
  61771. break;
  61772. case BABYLON.Mesh.CAP_START:
  61773. shapePaths[0] = capPath(shapePaths[2]);
  61774. shapePaths[1] = shapePaths[2];
  61775. break;
  61776. case BABYLON.Mesh.CAP_END:
  61777. shapePaths[index] = shapePaths[index - 1];
  61778. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61779. break;
  61780. case BABYLON.Mesh.CAP_ALL:
  61781. shapePaths[0] = capPath(shapePaths[2]);
  61782. shapePaths[1] = shapePaths[2];
  61783. shapePaths[index] = shapePaths[index - 1];
  61784. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61785. break;
  61786. default:
  61787. break;
  61788. }
  61789. return shapePaths;
  61790. };
  61791. var path3D;
  61792. var pathArray;
  61793. if (instance) { // instance update
  61794. path3D = (instance.path3D).update(curve);
  61795. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61796. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61797. return instance;
  61798. }
  61799. // extruded shape creation
  61800. path3D = new BABYLON.Path3D(curve);
  61801. var newShapePaths = new Array();
  61802. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61803. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61804. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61805. extrudedGeneric.pathArray = pathArray;
  61806. extrudedGeneric.path3D = path3D;
  61807. extrudedGeneric.cap = cap;
  61808. return extrudedGeneric;
  61809. };
  61810. return MeshBuilder;
  61811. }());
  61812. BABYLON.MeshBuilder = MeshBuilder;
  61813. })(BABYLON || (BABYLON = {}));
  61814. //# sourceMappingURL=babylon.meshBuilder.js.map
  61815. var BABYLON;
  61816. (function (BABYLON) {
  61817. /**
  61818. * Draco compression (https://google.github.io/draco/)
  61819. *
  61820. * This class wraps the Draco module.
  61821. *
  61822. * **Encoder**
  61823. *
  61824. * The encoder is not currently implemented.
  61825. *
  61826. * **Decoder**
  61827. *
  61828. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61829. *
  61830. * To update the configuration, use the following code:
  61831. * ```javascript
  61832. * BABYLON.DracoCompression.Configuration = {
  61833. * decoder: {
  61834. * wasmUrl: "<url to the WebAssembly library>",
  61835. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61836. * fallbackUrl: "<url to the fallback JavaScript library>",
  61837. * }
  61838. * };
  61839. * ```
  61840. *
  61841. * 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.
  61842. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61843. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61844. *
  61845. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61846. * ```javascript
  61847. * var dracoCompression = new BABYLON.DracoCompression();
  61848. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61849. * [BABYLON.VertexBuffer.PositionKind]: 0
  61850. * });
  61851. * ```
  61852. *
  61853. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61854. */
  61855. var DracoCompression = /** @class */ (function () {
  61856. /**
  61857. * Constructor
  61858. */
  61859. function DracoCompression() {
  61860. }
  61861. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61862. /**
  61863. * Returns true if the decoder is available.
  61864. */
  61865. get: function () {
  61866. if (typeof DracoDecoderModule !== "undefined") {
  61867. return true;
  61868. }
  61869. var decoder = DracoCompression.Configuration.decoder;
  61870. if (decoder) {
  61871. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61872. return true;
  61873. }
  61874. if (decoder.fallbackUrl) {
  61875. return true;
  61876. }
  61877. }
  61878. return false;
  61879. },
  61880. enumerable: true,
  61881. configurable: true
  61882. });
  61883. /**
  61884. * Stop all async operations and release resources.
  61885. */
  61886. DracoCompression.prototype.dispose = function () {
  61887. };
  61888. /**
  61889. * Decode Draco compressed mesh data to vertex data.
  61890. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61891. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61892. * @returns A promise that resolves with the decoded vertex data
  61893. */
  61894. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61895. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61896. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61897. var module = wrappedModule.module;
  61898. var vertexData = new BABYLON.VertexData();
  61899. var buffer = new module.DecoderBuffer();
  61900. buffer.Init(dataView, dataView.byteLength);
  61901. var decoder = new module.Decoder();
  61902. var geometry;
  61903. var status;
  61904. try {
  61905. var type = decoder.GetEncodedGeometryType(buffer);
  61906. switch (type) {
  61907. case module.TRIANGULAR_MESH:
  61908. geometry = new module.Mesh();
  61909. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61910. break;
  61911. case module.POINT_CLOUD:
  61912. geometry = new module.PointCloud();
  61913. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61914. break;
  61915. default:
  61916. throw new Error("Invalid geometry type " + type);
  61917. }
  61918. if (!status.ok() || !geometry.ptr) {
  61919. throw new Error(status.error_msg());
  61920. }
  61921. var numPoints = geometry.num_points();
  61922. if (type === module.TRIANGULAR_MESH) {
  61923. var numFaces = geometry.num_faces();
  61924. var faceIndices = new module.DracoInt32Array();
  61925. try {
  61926. var indices = new Uint32Array(numFaces * 3);
  61927. for (var i = 0; i < numFaces; i++) {
  61928. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61929. var offset = i * 3;
  61930. indices[offset + 0] = faceIndices.GetValue(0);
  61931. indices[offset + 1] = faceIndices.GetValue(1);
  61932. indices[offset + 2] = faceIndices.GetValue(2);
  61933. }
  61934. vertexData.indices = indices;
  61935. }
  61936. finally {
  61937. module.destroy(faceIndices);
  61938. }
  61939. }
  61940. for (var kind in attributes) {
  61941. var uniqueId = attributes[kind];
  61942. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61943. var dracoData = new module.DracoFloat32Array();
  61944. try {
  61945. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61946. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61947. for (var i = 0; i < babylonData.length; i++) {
  61948. babylonData[i] = dracoData.GetValue(i);
  61949. }
  61950. vertexData.set(babylonData, kind);
  61951. }
  61952. finally {
  61953. module.destroy(dracoData);
  61954. }
  61955. }
  61956. }
  61957. finally {
  61958. if (geometry) {
  61959. module.destroy(geometry);
  61960. }
  61961. module.destroy(decoder);
  61962. module.destroy(buffer);
  61963. }
  61964. return vertexData;
  61965. });
  61966. };
  61967. DracoCompression._GetDecoderModule = function () {
  61968. if (!DracoCompression._DecoderModulePromise) {
  61969. var promise = null;
  61970. var config_1 = {};
  61971. if (typeof DracoDecoderModule !== "undefined") {
  61972. promise = Promise.resolve();
  61973. }
  61974. else {
  61975. var decoder = DracoCompression.Configuration.decoder;
  61976. if (decoder) {
  61977. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61978. promise = Promise.all([
  61979. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61980. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61981. config_1.wasmBinary = data;
  61982. })
  61983. ]);
  61984. }
  61985. else if (decoder.fallbackUrl) {
  61986. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61987. }
  61988. }
  61989. }
  61990. if (!promise) {
  61991. throw new Error("Draco decoder module is not available");
  61992. }
  61993. DracoCompression._DecoderModulePromise = promise.then(function () {
  61994. return new Promise(function (resolve) {
  61995. config_1.onModuleLoaded = function (decoderModule) {
  61996. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61997. resolve({ module: decoderModule });
  61998. };
  61999. DracoDecoderModule(config_1);
  62000. });
  62001. });
  62002. }
  62003. return DracoCompression._DecoderModulePromise;
  62004. };
  62005. DracoCompression._LoadScriptAsync = function (url) {
  62006. return new Promise(function (resolve, reject) {
  62007. BABYLON.Tools.LoadScript(url, function () {
  62008. resolve();
  62009. }, function (message) {
  62010. reject(new Error(message));
  62011. });
  62012. });
  62013. };
  62014. DracoCompression._LoadFileAsync = function (url) {
  62015. return new Promise(function (resolve, reject) {
  62016. BABYLON.Tools.LoadFile(url, function (data) {
  62017. resolve(data);
  62018. }, undefined, undefined, true, function (request, exception) {
  62019. reject(exception);
  62020. });
  62021. });
  62022. };
  62023. /**
  62024. * The configuration. Defaults to the following urls:
  62025. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62026. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62027. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62028. */
  62029. DracoCompression.Configuration = {
  62030. decoder: {
  62031. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62032. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62033. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62034. }
  62035. };
  62036. return DracoCompression;
  62037. }());
  62038. BABYLON.DracoCompression = DracoCompression;
  62039. })(BABYLON || (BABYLON = {}));
  62040. //# sourceMappingURL=babylon.dracoCompression.js.map
  62041. var BABYLON;
  62042. (function (BABYLON) {
  62043. var AudioEngine = /** @class */ (function () {
  62044. function AudioEngine() {
  62045. this._audioContext = null;
  62046. this._audioContextInitialized = false;
  62047. this.canUseWebAudio = false;
  62048. this.WarnedWebAudioUnsupported = false;
  62049. this.unlocked = false;
  62050. this.isMP3supported = false;
  62051. this.isOGGsupported = false;
  62052. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62053. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62054. this.canUseWebAudio = true;
  62055. }
  62056. var audioElem = document.createElement('audio');
  62057. try {
  62058. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62059. this.isMP3supported = true;
  62060. }
  62061. }
  62062. catch (e) {
  62063. // protect error during capability check.
  62064. }
  62065. try {
  62066. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62067. this.isOGGsupported = true;
  62068. }
  62069. }
  62070. catch (e) {
  62071. // protect error during capability check.
  62072. }
  62073. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62074. this._unlockiOSaudio();
  62075. }
  62076. else {
  62077. this.unlocked = true;
  62078. }
  62079. }
  62080. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62081. get: function () {
  62082. if (!this._audioContextInitialized) {
  62083. this._initializeAudioContext();
  62084. }
  62085. return this._audioContext;
  62086. },
  62087. enumerable: true,
  62088. configurable: true
  62089. });
  62090. AudioEngine.prototype._unlockiOSaudio = function () {
  62091. var _this = this;
  62092. var unlockaudio = function () {
  62093. if (!_this.audioContext) {
  62094. return;
  62095. }
  62096. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62097. var source = _this.audioContext.createBufferSource();
  62098. source.buffer = buffer;
  62099. source.connect(_this.audioContext.destination);
  62100. source.start(0);
  62101. setTimeout(function () {
  62102. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62103. _this.unlocked = true;
  62104. window.removeEventListener('touchend', unlockaudio, false);
  62105. if (_this.onAudioUnlocked) {
  62106. _this.onAudioUnlocked();
  62107. }
  62108. }
  62109. }, 0);
  62110. };
  62111. window.addEventListener('touchend', unlockaudio, false);
  62112. };
  62113. AudioEngine.prototype._initializeAudioContext = function () {
  62114. try {
  62115. if (this.canUseWebAudio) {
  62116. this._audioContext = new AudioContext();
  62117. // create a global volume gain node
  62118. this.masterGain = this._audioContext.createGain();
  62119. this.masterGain.gain.value = 1;
  62120. this.masterGain.connect(this._audioContext.destination);
  62121. this._audioContextInitialized = true;
  62122. }
  62123. }
  62124. catch (e) {
  62125. this.canUseWebAudio = false;
  62126. BABYLON.Tools.Error("Web Audio: " + e.message);
  62127. }
  62128. };
  62129. AudioEngine.prototype.dispose = function () {
  62130. if (this.canUseWebAudio && this._audioContextInitialized) {
  62131. if (this._connectedAnalyser && this._audioContext) {
  62132. this._connectedAnalyser.stopDebugCanvas();
  62133. this._connectedAnalyser.dispose();
  62134. this.masterGain.disconnect();
  62135. this.masterGain.connect(this._audioContext.destination);
  62136. this._connectedAnalyser = null;
  62137. }
  62138. this.masterGain.gain.value = 1;
  62139. }
  62140. this.WarnedWebAudioUnsupported = false;
  62141. };
  62142. AudioEngine.prototype.getGlobalVolume = function () {
  62143. if (this.canUseWebAudio && this._audioContextInitialized) {
  62144. return this.masterGain.gain.value;
  62145. }
  62146. else {
  62147. return -1;
  62148. }
  62149. };
  62150. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62151. if (this.canUseWebAudio && this._audioContextInitialized) {
  62152. this.masterGain.gain.value = newVolume;
  62153. }
  62154. };
  62155. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62156. if (this._connectedAnalyser) {
  62157. this._connectedAnalyser.stopDebugCanvas();
  62158. }
  62159. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62160. this._connectedAnalyser = analyser;
  62161. this.masterGain.disconnect();
  62162. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62163. }
  62164. };
  62165. return AudioEngine;
  62166. }());
  62167. BABYLON.AudioEngine = AudioEngine;
  62168. })(BABYLON || (BABYLON = {}));
  62169. //# sourceMappingURL=babylon.audioEngine.js.map
  62170. var BABYLON;
  62171. (function (BABYLON) {
  62172. var Sound = /** @class */ (function () {
  62173. /**
  62174. * Create a sound and attach it to a scene
  62175. * @param name Name of your sound
  62176. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62177. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62178. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62179. */
  62180. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62181. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62182. var _this = this;
  62183. this.autoplay = false;
  62184. this.loop = false;
  62185. this.useCustomAttenuation = false;
  62186. this.spatialSound = false;
  62187. this.refDistance = 1;
  62188. this.rolloffFactor = 1;
  62189. this.maxDistance = 100;
  62190. this.distanceModel = "linear";
  62191. this._panningModel = "equalpower";
  62192. this._playbackRate = 1;
  62193. this._streaming = false;
  62194. this._startTime = 0;
  62195. this._startOffset = 0;
  62196. this._position = BABYLON.Vector3.Zero();
  62197. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62198. this._volume = 1;
  62199. this._isReadyToPlay = false;
  62200. this.isPlaying = false;
  62201. this.isPaused = false;
  62202. this._isDirectional = false;
  62203. // Used if you'd like to create a directional sound.
  62204. // If not set, the sound will be omnidirectional
  62205. this._coneInnerAngle = 360;
  62206. this._coneOuterAngle = 360;
  62207. this._coneOuterGain = 0;
  62208. this._isOutputConnected = false;
  62209. this._urlType = "Unknown";
  62210. this.name = name;
  62211. this._scene = scene;
  62212. this._readyToPlayCallback = readyToPlayCallback;
  62213. // Default custom attenuation function is a linear attenuation
  62214. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62215. if (currentDistance < maxDistance) {
  62216. return currentVolume * (1 - currentDistance / maxDistance);
  62217. }
  62218. else {
  62219. return 0;
  62220. }
  62221. };
  62222. if (options) {
  62223. this.autoplay = options.autoplay || false;
  62224. this.loop = options.loop || false;
  62225. // if volume === 0, we need another way to check this option
  62226. if (options.volume !== undefined) {
  62227. this._volume = options.volume;
  62228. }
  62229. this.spatialSound = options.spatialSound || false;
  62230. this.maxDistance = options.maxDistance || 100;
  62231. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62232. this.rolloffFactor = options.rolloffFactor || 1;
  62233. this.refDistance = options.refDistance || 1;
  62234. this.distanceModel = options.distanceModel || "linear";
  62235. this._playbackRate = options.playbackRate || 1;
  62236. this._streaming = options.streaming || false;
  62237. }
  62238. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62239. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62240. this._soundGain.gain.value = this._volume;
  62241. this._inputAudioNode = this._soundGain;
  62242. this._ouputAudioNode = this._soundGain;
  62243. if (this.spatialSound) {
  62244. this._createSpatialParameters();
  62245. }
  62246. this._scene.mainSoundTrack.AddSound(this);
  62247. var validParameter = true;
  62248. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62249. if (urlOrArrayBuffer) {
  62250. try {
  62251. if (typeof (urlOrArrayBuffer) === "string") {
  62252. this._urlType = "String";
  62253. }
  62254. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62255. this._urlType = "ArrayBuffer";
  62256. }
  62257. else if (urlOrArrayBuffer instanceof MediaStream) {
  62258. this._urlType = "MediaStream";
  62259. }
  62260. else if (Array.isArray(urlOrArrayBuffer)) {
  62261. this._urlType = "Array";
  62262. }
  62263. var urls = [];
  62264. var codecSupportedFound = false;
  62265. switch (this._urlType) {
  62266. case "MediaStream":
  62267. this._streaming = true;
  62268. this._isReadyToPlay = true;
  62269. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62270. if (this.autoplay) {
  62271. this.play();
  62272. }
  62273. if (this._readyToPlayCallback) {
  62274. this._readyToPlayCallback();
  62275. }
  62276. break;
  62277. case "ArrayBuffer":
  62278. if (urlOrArrayBuffer.byteLength > 0) {
  62279. codecSupportedFound = true;
  62280. this._soundLoaded(urlOrArrayBuffer);
  62281. }
  62282. break;
  62283. case "String":
  62284. urls.push(urlOrArrayBuffer);
  62285. case "Array":
  62286. if (urls.length === 0)
  62287. urls = urlOrArrayBuffer;
  62288. // If we found a supported format, we load it immediately and stop the loop
  62289. for (var i = 0; i < urls.length; i++) {
  62290. var url = urls[i];
  62291. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62292. codecSupportedFound = true;
  62293. }
  62294. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62295. codecSupportedFound = true;
  62296. }
  62297. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62298. codecSupportedFound = true;
  62299. }
  62300. if (url.indexOf("blob:") !== -1) {
  62301. codecSupportedFound = true;
  62302. }
  62303. if (codecSupportedFound) {
  62304. // Loading sound using XHR2
  62305. if (!this._streaming) {
  62306. this._scene._loadFile(url, function (data) {
  62307. _this._soundLoaded(data);
  62308. }, undefined, true, true, function (exception) {
  62309. if (exception) {
  62310. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62311. }
  62312. BABYLON.Tools.Error("Sound creation aborted.");
  62313. _this._scene.mainSoundTrack.RemoveSound(_this);
  62314. });
  62315. }
  62316. // Streaming sound using HTML5 Audio tag
  62317. else {
  62318. this._htmlAudioElement = new Audio(url);
  62319. this._htmlAudioElement.controls = false;
  62320. this._htmlAudioElement.loop = this.loop;
  62321. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62322. this._htmlAudioElement.preload = "auto";
  62323. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62324. _this._isReadyToPlay = true;
  62325. if (_this.autoplay) {
  62326. _this.play();
  62327. }
  62328. if (_this._readyToPlayCallback) {
  62329. _this._readyToPlayCallback();
  62330. }
  62331. });
  62332. document.body.appendChild(this._htmlAudioElement);
  62333. }
  62334. break;
  62335. }
  62336. }
  62337. break;
  62338. default:
  62339. validParameter = false;
  62340. break;
  62341. }
  62342. if (!validParameter) {
  62343. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62344. }
  62345. else {
  62346. if (!codecSupportedFound) {
  62347. this._isReadyToPlay = true;
  62348. // Simulating a ready to play event to avoid breaking code path
  62349. if (this._readyToPlayCallback) {
  62350. window.setTimeout(function () {
  62351. if (_this._readyToPlayCallback) {
  62352. _this._readyToPlayCallback();
  62353. }
  62354. }, 1000);
  62355. }
  62356. }
  62357. }
  62358. }
  62359. catch (ex) {
  62360. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62361. this._scene.mainSoundTrack.RemoveSound(this);
  62362. }
  62363. }
  62364. }
  62365. else {
  62366. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62367. this._scene.mainSoundTrack.AddSound(this);
  62368. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62369. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62370. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62371. }
  62372. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62373. if (this._readyToPlayCallback) {
  62374. window.setTimeout(function () {
  62375. if (_this._readyToPlayCallback) {
  62376. _this._readyToPlayCallback();
  62377. }
  62378. }, 1000);
  62379. }
  62380. }
  62381. }
  62382. Sound.prototype.dispose = function () {
  62383. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62384. if (this.isPlaying) {
  62385. this.stop();
  62386. }
  62387. this._isReadyToPlay = false;
  62388. if (this.soundTrackId === -1) {
  62389. this._scene.mainSoundTrack.RemoveSound(this);
  62390. }
  62391. else {
  62392. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62393. }
  62394. if (this._soundGain) {
  62395. this._soundGain.disconnect();
  62396. this._soundGain = null;
  62397. }
  62398. if (this._soundPanner) {
  62399. this._soundPanner.disconnect();
  62400. this._soundPanner = null;
  62401. }
  62402. if (this._soundSource) {
  62403. this._soundSource.disconnect();
  62404. this._soundSource = null;
  62405. }
  62406. this._audioBuffer = null;
  62407. if (this._htmlAudioElement) {
  62408. this._htmlAudioElement.pause();
  62409. this._htmlAudioElement.src = "";
  62410. document.body.removeChild(this._htmlAudioElement);
  62411. }
  62412. if (this._streamingSource) {
  62413. this._streamingSource.disconnect();
  62414. }
  62415. if (this._connectedMesh && this._registerFunc) {
  62416. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62417. this._connectedMesh = null;
  62418. }
  62419. }
  62420. };
  62421. Sound.prototype.isReady = function () {
  62422. return this._isReadyToPlay;
  62423. };
  62424. Sound.prototype._soundLoaded = function (audioData) {
  62425. var _this = this;
  62426. if (!BABYLON.Engine.audioEngine.audioContext) {
  62427. return;
  62428. }
  62429. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62430. _this._audioBuffer = buffer;
  62431. _this._isReadyToPlay = true;
  62432. if (_this.autoplay) {
  62433. _this.play();
  62434. }
  62435. if (_this._readyToPlayCallback) {
  62436. _this._readyToPlayCallback();
  62437. }
  62438. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62439. };
  62440. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62441. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62442. this._audioBuffer = audioBuffer;
  62443. this._isReadyToPlay = true;
  62444. }
  62445. };
  62446. Sound.prototype.updateOptions = function (options) {
  62447. if (options) {
  62448. this.loop = options.loop || this.loop;
  62449. this.maxDistance = options.maxDistance || this.maxDistance;
  62450. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62451. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62452. this.refDistance = options.refDistance || this.refDistance;
  62453. this.distanceModel = options.distanceModel || this.distanceModel;
  62454. this._playbackRate = options.playbackRate || this._playbackRate;
  62455. this._updateSpatialParameters();
  62456. if (this.isPlaying) {
  62457. if (this._streaming && this._htmlAudioElement) {
  62458. this._htmlAudioElement.playbackRate = this._playbackRate;
  62459. }
  62460. else {
  62461. if (this._soundSource) {
  62462. this._soundSource.playbackRate.value = this._playbackRate;
  62463. }
  62464. }
  62465. }
  62466. }
  62467. };
  62468. Sound.prototype._createSpatialParameters = function () {
  62469. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62470. if (this._scene.headphone) {
  62471. this._panningModel = "HRTF";
  62472. }
  62473. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62474. this._updateSpatialParameters();
  62475. this._soundPanner.connect(this._ouputAudioNode);
  62476. this._inputAudioNode = this._soundPanner;
  62477. }
  62478. };
  62479. Sound.prototype._updateSpatialParameters = function () {
  62480. if (this.spatialSound && this._soundPanner) {
  62481. if (this.useCustomAttenuation) {
  62482. // Tricks to disable in a way embedded Web Audio attenuation
  62483. this._soundPanner.distanceModel = "linear";
  62484. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62485. this._soundPanner.refDistance = 1;
  62486. this._soundPanner.rolloffFactor = 1;
  62487. this._soundPanner.panningModel = this._panningModel;
  62488. }
  62489. else {
  62490. this._soundPanner.distanceModel = this.distanceModel;
  62491. this._soundPanner.maxDistance = this.maxDistance;
  62492. this._soundPanner.refDistance = this.refDistance;
  62493. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62494. this._soundPanner.panningModel = this._panningModel;
  62495. }
  62496. }
  62497. };
  62498. Sound.prototype.switchPanningModelToHRTF = function () {
  62499. this._panningModel = "HRTF";
  62500. this._switchPanningModel();
  62501. };
  62502. Sound.prototype.switchPanningModelToEqualPower = function () {
  62503. this._panningModel = "equalpower";
  62504. this._switchPanningModel();
  62505. };
  62506. Sound.prototype._switchPanningModel = function () {
  62507. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62508. this._soundPanner.panningModel = this._panningModel;
  62509. }
  62510. };
  62511. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62512. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62513. if (this._isOutputConnected) {
  62514. this._ouputAudioNode.disconnect();
  62515. }
  62516. this._ouputAudioNode.connect(soundTrackAudioNode);
  62517. this._isOutputConnected = true;
  62518. }
  62519. };
  62520. /**
  62521. * Transform this sound into a directional source
  62522. * @param coneInnerAngle Size of the inner cone in degree
  62523. * @param coneOuterAngle Size of the outer cone in degree
  62524. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62525. */
  62526. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62527. if (coneOuterAngle < coneInnerAngle) {
  62528. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62529. return;
  62530. }
  62531. this._coneInnerAngle = coneInnerAngle;
  62532. this._coneOuterAngle = coneOuterAngle;
  62533. this._coneOuterGain = coneOuterGain;
  62534. this._isDirectional = true;
  62535. if (this.isPlaying && this.loop) {
  62536. this.stop();
  62537. this.play();
  62538. }
  62539. };
  62540. Sound.prototype.setPosition = function (newPosition) {
  62541. this._position = newPosition;
  62542. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62543. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62544. }
  62545. };
  62546. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62547. this._localDirection = newLocalDirection;
  62548. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62549. this._updateDirection();
  62550. }
  62551. };
  62552. Sound.prototype._updateDirection = function () {
  62553. if (!this._connectedMesh || !this._soundPanner) {
  62554. return;
  62555. }
  62556. var mat = this._connectedMesh.getWorldMatrix();
  62557. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62558. direction.normalize();
  62559. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62560. };
  62561. Sound.prototype.updateDistanceFromListener = function () {
  62562. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62563. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62564. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62565. }
  62566. };
  62567. Sound.prototype.setAttenuationFunction = function (callback) {
  62568. this._customAttenuationFunction = callback;
  62569. };
  62570. /**
  62571. * Play the sound
  62572. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62573. * @param offset (optional) Start the sound setting it at a specific time
  62574. */
  62575. Sound.prototype.play = function (time, offset) {
  62576. var _this = this;
  62577. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62578. try {
  62579. if (this._startOffset < 0) {
  62580. time = -this._startOffset;
  62581. this._startOffset = 0;
  62582. }
  62583. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62584. if (!this._soundSource || !this._streamingSource) {
  62585. if (this.spatialSound && this._soundPanner) {
  62586. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62587. if (this._isDirectional) {
  62588. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62589. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62590. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62591. if (this._connectedMesh) {
  62592. this._updateDirection();
  62593. }
  62594. else {
  62595. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62596. }
  62597. }
  62598. }
  62599. }
  62600. if (this._streaming) {
  62601. if (!this._streamingSource) {
  62602. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62603. this._htmlAudioElement.onended = function () { _this._onended(); };
  62604. this._htmlAudioElement.playbackRate = this._playbackRate;
  62605. }
  62606. this._streamingSource.disconnect();
  62607. this._streamingSource.connect(this._inputAudioNode);
  62608. if (this._htmlAudioElement) {
  62609. this._htmlAudioElement.play();
  62610. }
  62611. }
  62612. else {
  62613. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62614. this._soundSource.buffer = this._audioBuffer;
  62615. this._soundSource.connect(this._inputAudioNode);
  62616. this._soundSource.loop = this.loop;
  62617. this._soundSource.playbackRate.value = this._playbackRate;
  62618. this._soundSource.onended = function () { _this._onended(); };
  62619. if (this._soundSource.buffer) {
  62620. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62621. }
  62622. }
  62623. this._startTime = startTime;
  62624. this.isPlaying = true;
  62625. this.isPaused = false;
  62626. }
  62627. catch (ex) {
  62628. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62629. }
  62630. }
  62631. };
  62632. Sound.prototype._onended = function () {
  62633. this.isPlaying = false;
  62634. if (this.onended) {
  62635. this.onended();
  62636. }
  62637. };
  62638. /**
  62639. * Stop the sound
  62640. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62641. */
  62642. Sound.prototype.stop = function (time) {
  62643. if (this.isPlaying) {
  62644. if (this._streaming) {
  62645. if (this._htmlAudioElement) {
  62646. this._htmlAudioElement.pause();
  62647. // Test needed for Firefox or it will generate an Invalid State Error
  62648. if (this._htmlAudioElement.currentTime > 0) {
  62649. this._htmlAudioElement.currentTime = 0;
  62650. }
  62651. }
  62652. else {
  62653. this._streamingSource.disconnect();
  62654. }
  62655. }
  62656. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62657. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62658. this._soundSource.stop(stopTime);
  62659. this._soundSource.onended = function () { };
  62660. if (!this.isPaused) {
  62661. this._startOffset = 0;
  62662. }
  62663. }
  62664. this.isPlaying = false;
  62665. }
  62666. };
  62667. Sound.prototype.pause = function () {
  62668. if (this.isPlaying) {
  62669. this.isPaused = true;
  62670. if (this._streaming) {
  62671. if (this._htmlAudioElement) {
  62672. this._htmlAudioElement.pause();
  62673. }
  62674. else {
  62675. this._streamingSource.disconnect();
  62676. }
  62677. }
  62678. else if (BABYLON.Engine.audioEngine.audioContext) {
  62679. this.stop(0);
  62680. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62681. }
  62682. }
  62683. };
  62684. Sound.prototype.setVolume = function (newVolume, time) {
  62685. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62686. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62687. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62688. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62689. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62690. }
  62691. else {
  62692. this._soundGain.gain.value = newVolume;
  62693. }
  62694. }
  62695. this._volume = newVolume;
  62696. };
  62697. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62698. this._playbackRate = newPlaybackRate;
  62699. if (this.isPlaying) {
  62700. if (this._streaming && this._htmlAudioElement) {
  62701. this._htmlAudioElement.playbackRate = this._playbackRate;
  62702. }
  62703. else if (this._soundSource) {
  62704. this._soundSource.playbackRate.value = this._playbackRate;
  62705. }
  62706. }
  62707. };
  62708. Sound.prototype.getVolume = function () {
  62709. return this._volume;
  62710. };
  62711. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62712. var _this = this;
  62713. if (this._connectedMesh && this._registerFunc) {
  62714. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62715. this._registerFunc = null;
  62716. }
  62717. this._connectedMesh = meshToConnectTo;
  62718. if (!this.spatialSound) {
  62719. this.spatialSound = true;
  62720. this._createSpatialParameters();
  62721. if (this.isPlaying && this.loop) {
  62722. this.stop();
  62723. this.play();
  62724. }
  62725. }
  62726. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62727. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62728. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62729. };
  62730. Sound.prototype.detachFromMesh = function () {
  62731. if (this._connectedMesh && this._registerFunc) {
  62732. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62733. this._registerFunc = null;
  62734. this._connectedMesh = null;
  62735. }
  62736. };
  62737. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62738. if (!node.getBoundingInfo) {
  62739. return;
  62740. }
  62741. var mesh = node;
  62742. var boundingInfo = mesh.getBoundingInfo();
  62743. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62744. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62745. this._updateDirection();
  62746. }
  62747. };
  62748. Sound.prototype.clone = function () {
  62749. var _this = this;
  62750. if (!this._streaming) {
  62751. var setBufferAndRun = function () {
  62752. if (_this._isReadyToPlay) {
  62753. clonedSound._audioBuffer = _this.getAudioBuffer();
  62754. clonedSound._isReadyToPlay = true;
  62755. if (clonedSound.autoplay) {
  62756. clonedSound.play();
  62757. }
  62758. }
  62759. else {
  62760. window.setTimeout(setBufferAndRun, 300);
  62761. }
  62762. };
  62763. var currentOptions = {
  62764. autoplay: this.autoplay, loop: this.loop,
  62765. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62766. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62767. refDistance: this.refDistance, distanceModel: this.distanceModel
  62768. };
  62769. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62770. if (this.useCustomAttenuation) {
  62771. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62772. }
  62773. clonedSound.setPosition(this._position);
  62774. clonedSound.setPlaybackRate(this._playbackRate);
  62775. setBufferAndRun();
  62776. return clonedSound;
  62777. }
  62778. // Can't clone a streaming sound
  62779. else {
  62780. return null;
  62781. }
  62782. };
  62783. Sound.prototype.getAudioBuffer = function () {
  62784. return this._audioBuffer;
  62785. };
  62786. Sound.prototype.serialize = function () {
  62787. var serializationObject = {
  62788. name: this.name,
  62789. url: this.name,
  62790. autoplay: this.autoplay,
  62791. loop: this.loop,
  62792. volume: this._volume,
  62793. spatialSound: this.spatialSound,
  62794. maxDistance: this.maxDistance,
  62795. rolloffFactor: this.rolloffFactor,
  62796. refDistance: this.refDistance,
  62797. distanceModel: this.distanceModel,
  62798. playbackRate: this._playbackRate,
  62799. panningModel: this._panningModel,
  62800. soundTrackId: this.soundTrackId
  62801. };
  62802. if (this.spatialSound) {
  62803. if (this._connectedMesh)
  62804. serializationObject.connectedMeshId = this._connectedMesh.id;
  62805. serializationObject.position = this._position.asArray();
  62806. serializationObject.refDistance = this.refDistance;
  62807. serializationObject.distanceModel = this.distanceModel;
  62808. serializationObject.isDirectional = this._isDirectional;
  62809. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62810. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62811. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62812. serializationObject.coneOuterGain = this._coneOuterGain;
  62813. }
  62814. return serializationObject;
  62815. };
  62816. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62817. var soundName = parsedSound.name;
  62818. var soundUrl;
  62819. if (parsedSound.url) {
  62820. soundUrl = rootUrl + parsedSound.url;
  62821. }
  62822. else {
  62823. soundUrl = rootUrl + soundName;
  62824. }
  62825. var options = {
  62826. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62827. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62828. rolloffFactor: parsedSound.rolloffFactor,
  62829. refDistance: parsedSound.refDistance,
  62830. distanceModel: parsedSound.distanceModel,
  62831. playbackRate: parsedSound.playbackRate
  62832. };
  62833. var newSound;
  62834. if (!sourceSound) {
  62835. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62836. scene._addPendingData(newSound);
  62837. }
  62838. else {
  62839. var setBufferAndRun = function () {
  62840. if (sourceSound._isReadyToPlay) {
  62841. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62842. newSound._isReadyToPlay = true;
  62843. if (newSound.autoplay) {
  62844. newSound.play();
  62845. }
  62846. }
  62847. else {
  62848. window.setTimeout(setBufferAndRun, 300);
  62849. }
  62850. };
  62851. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62852. setBufferAndRun();
  62853. }
  62854. if (parsedSound.position) {
  62855. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62856. newSound.setPosition(soundPosition);
  62857. }
  62858. if (parsedSound.isDirectional) {
  62859. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62860. if (parsedSound.localDirectionToMesh) {
  62861. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62862. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62863. }
  62864. }
  62865. if (parsedSound.connectedMeshId) {
  62866. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62867. if (connectedMesh) {
  62868. newSound.attachToMesh(connectedMesh);
  62869. }
  62870. }
  62871. return newSound;
  62872. };
  62873. return Sound;
  62874. }());
  62875. BABYLON.Sound = Sound;
  62876. })(BABYLON || (BABYLON = {}));
  62877. //# sourceMappingURL=babylon.sound.js.map
  62878. var BABYLON;
  62879. (function (BABYLON) {
  62880. var SoundTrack = /** @class */ (function () {
  62881. function SoundTrack(scene, options) {
  62882. this.id = -1;
  62883. this._isMainTrack = false;
  62884. this._isInitialized = false;
  62885. this._scene = scene;
  62886. this.soundCollection = new Array();
  62887. this._options = options;
  62888. if (!this._isMainTrack) {
  62889. this._scene.soundTracks.push(this);
  62890. this.id = this._scene.soundTracks.length - 1;
  62891. }
  62892. }
  62893. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62894. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62895. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62896. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62897. if (this._options) {
  62898. if (this._options.volume) {
  62899. this._outputAudioNode.gain.value = this._options.volume;
  62900. }
  62901. if (this._options.mainTrack) {
  62902. this._isMainTrack = this._options.mainTrack;
  62903. }
  62904. }
  62905. this._isInitialized = true;
  62906. }
  62907. };
  62908. SoundTrack.prototype.dispose = function () {
  62909. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62910. if (this._connectedAnalyser) {
  62911. this._connectedAnalyser.stopDebugCanvas();
  62912. }
  62913. while (this.soundCollection.length) {
  62914. this.soundCollection[0].dispose();
  62915. }
  62916. if (this._outputAudioNode) {
  62917. this._outputAudioNode.disconnect();
  62918. }
  62919. this._outputAudioNode = null;
  62920. }
  62921. };
  62922. SoundTrack.prototype.AddSound = function (sound) {
  62923. if (!this._isInitialized) {
  62924. this._initializeSoundTrackAudioGraph();
  62925. }
  62926. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62927. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62928. }
  62929. if (sound.soundTrackId) {
  62930. if (sound.soundTrackId === -1) {
  62931. this._scene.mainSoundTrack.RemoveSound(sound);
  62932. }
  62933. else {
  62934. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62935. }
  62936. }
  62937. this.soundCollection.push(sound);
  62938. sound.soundTrackId = this.id;
  62939. };
  62940. SoundTrack.prototype.RemoveSound = function (sound) {
  62941. var index = this.soundCollection.indexOf(sound);
  62942. if (index !== -1) {
  62943. this.soundCollection.splice(index, 1);
  62944. }
  62945. };
  62946. SoundTrack.prototype.setVolume = function (newVolume) {
  62947. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62948. this._outputAudioNode.gain.value = newVolume;
  62949. }
  62950. };
  62951. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62952. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62953. for (var i = 0; i < this.soundCollection.length; i++) {
  62954. this.soundCollection[i].switchPanningModelToHRTF();
  62955. }
  62956. }
  62957. };
  62958. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62960. for (var i = 0; i < this.soundCollection.length; i++) {
  62961. this.soundCollection[i].switchPanningModelToEqualPower();
  62962. }
  62963. }
  62964. };
  62965. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62966. if (this._connectedAnalyser) {
  62967. this._connectedAnalyser.stopDebugCanvas();
  62968. }
  62969. this._connectedAnalyser = analyser;
  62970. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62971. this._outputAudioNode.disconnect();
  62972. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62973. }
  62974. };
  62975. return SoundTrack;
  62976. }());
  62977. BABYLON.SoundTrack = SoundTrack;
  62978. })(BABYLON || (BABYLON = {}));
  62979. //# sourceMappingURL=babylon.soundtrack.js.map
  62980. var BABYLON;
  62981. (function (BABYLON) {
  62982. /**
  62983. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62984. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62985. */
  62986. var Analyser = /** @class */ (function () {
  62987. /**
  62988. * Creates a new analyser
  62989. * @param scene defines hosting scene
  62990. */
  62991. function Analyser(scene) {
  62992. /**
  62993. * Gets or sets the smoothing
  62994. * @ignorenaming
  62995. */
  62996. this.SMOOTHING = 0.75;
  62997. /**
  62998. * Gets or sets the FFT table size
  62999. * @ignorenaming
  63000. */
  63001. this.FFT_SIZE = 512;
  63002. /**
  63003. * Gets or sets the bar graph amplitude
  63004. * @ignorenaming
  63005. */
  63006. this.BARGRAPHAMPLITUDE = 256;
  63007. /**
  63008. * Gets or sets the position of the debug canvas
  63009. * @ignorenaming
  63010. */
  63011. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63012. /**
  63013. * Gets or sets the debug canvas size
  63014. * @ignorenaming
  63015. */
  63016. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63017. this._scene = scene;
  63018. this._audioEngine = BABYLON.Engine.audioEngine;
  63019. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63020. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63021. this._webAudioAnalyser.minDecibels = -140;
  63022. this._webAudioAnalyser.maxDecibels = 0;
  63023. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63024. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63025. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63026. }
  63027. }
  63028. /**
  63029. * Get the number of data values you will have to play with for the visualization
  63030. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63031. * @returns a number
  63032. */
  63033. Analyser.prototype.getFrequencyBinCount = function () {
  63034. if (this._audioEngine.canUseWebAudio) {
  63035. return this._webAudioAnalyser.frequencyBinCount;
  63036. }
  63037. else {
  63038. return 0;
  63039. }
  63040. };
  63041. /**
  63042. * Gets the current frequency data as a byte array
  63043. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63044. * @returns a Uint8Array
  63045. */
  63046. Analyser.prototype.getByteFrequencyData = function () {
  63047. if (this._audioEngine.canUseWebAudio) {
  63048. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63049. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63050. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63051. }
  63052. return this._byteFreqs;
  63053. };
  63054. /**
  63055. * Gets the current waveform as a byte array
  63056. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63057. * @returns a Uint8Array
  63058. */
  63059. Analyser.prototype.getByteTimeDomainData = function () {
  63060. if (this._audioEngine.canUseWebAudio) {
  63061. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63062. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63063. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63064. }
  63065. return this._byteTime;
  63066. };
  63067. /**
  63068. * Gets the current frequency data as a float array
  63069. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63070. * @returns a Float32Array
  63071. */
  63072. Analyser.prototype.getFloatFrequencyData = function () {
  63073. if (this._audioEngine.canUseWebAudio) {
  63074. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63075. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63076. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63077. }
  63078. return this._floatFreqs;
  63079. };
  63080. /**
  63081. * Renders the debug canvas
  63082. */
  63083. Analyser.prototype.drawDebugCanvas = function () {
  63084. var _this = this;
  63085. if (this._audioEngine.canUseWebAudio) {
  63086. if (!this._debugCanvas) {
  63087. this._debugCanvas = document.createElement("canvas");
  63088. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63089. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63090. this._debugCanvas.style.position = "absolute";
  63091. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63092. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63093. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63094. document.body.appendChild(this._debugCanvas);
  63095. this._registerFunc = function () {
  63096. _this.drawDebugCanvas();
  63097. };
  63098. this._scene.registerBeforeRender(this._registerFunc);
  63099. }
  63100. if (this._registerFunc && this._debugCanvasContext) {
  63101. var workingArray = this.getByteFrequencyData();
  63102. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63103. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63104. // Draw the frequency domain chart.
  63105. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63106. var value = workingArray[i];
  63107. var percent = value / this.BARGRAPHAMPLITUDE;
  63108. var height = this.DEBUGCANVASSIZE.height * percent;
  63109. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63110. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63111. var hue = i / this.getFrequencyBinCount() * 360;
  63112. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63113. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63114. }
  63115. }
  63116. }
  63117. };
  63118. /**
  63119. * Stops rendering the debug canvas and removes it
  63120. */
  63121. Analyser.prototype.stopDebugCanvas = function () {
  63122. if (this._debugCanvas) {
  63123. if (this._registerFunc) {
  63124. this._scene.unregisterBeforeRender(this._registerFunc);
  63125. this._registerFunc = null;
  63126. }
  63127. document.body.removeChild(this._debugCanvas);
  63128. this._debugCanvas = null;
  63129. this._debugCanvasContext = null;
  63130. }
  63131. };
  63132. /**
  63133. * Connects two audio nodes
  63134. * @param inputAudioNode defines first node to connect
  63135. * @param outputAudioNode defines second node to connect
  63136. */
  63137. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63138. if (this._audioEngine.canUseWebAudio) {
  63139. inputAudioNode.connect(this._webAudioAnalyser);
  63140. this._webAudioAnalyser.connect(outputAudioNode);
  63141. }
  63142. };
  63143. /**
  63144. * Releases all associated resources
  63145. */
  63146. Analyser.prototype.dispose = function () {
  63147. if (this._audioEngine.canUseWebAudio) {
  63148. this._webAudioAnalyser.disconnect();
  63149. }
  63150. };
  63151. return Analyser;
  63152. }());
  63153. BABYLON.Analyser = Analyser;
  63154. })(BABYLON || (BABYLON = {}));
  63155. //# sourceMappingURL=babylon.analyser.js.map
  63156. var BABYLON;
  63157. (function (BABYLON) {
  63158. var CubeTexture = /** @class */ (function (_super) {
  63159. __extends(CubeTexture, _super);
  63160. /**
  63161. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63162. * as prefiltered data.
  63163. * @param rootUrl defines the url of the texture or the root name of the six images
  63164. * @param scene defines the scene the texture is attached to
  63165. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63166. * @param noMipmap defines if mipmaps should be created or not
  63167. * @param files defines the six files to load for the different faces
  63168. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63169. * @param onError defines a callback triggered in case of error during load
  63170. * @param format defines the internal format to use for the texture once loaded
  63171. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63172. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63173. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63174. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63175. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63176. * @return the cube texture
  63177. */
  63178. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63179. if (extensions === void 0) { extensions = null; }
  63180. if (noMipmap === void 0) { noMipmap = false; }
  63181. if (files === void 0) { files = null; }
  63182. if (onLoad === void 0) { onLoad = null; }
  63183. if (onError === void 0) { onError = null; }
  63184. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63185. if (prefiltered === void 0) { prefiltered = false; }
  63186. if (forcedExtension === void 0) { forcedExtension = null; }
  63187. if (createPolynomials === void 0) { createPolynomials = false; }
  63188. if (lodScale === void 0) { lodScale = 0.8; }
  63189. if (lodOffset === void 0) { lodOffset = 0; }
  63190. var _this = _super.call(this, scene) || this;
  63191. /**
  63192. * Gets or sets the center of the bounding box associated with the cube texture
  63193. * It must define where the camera used to render the texture was set
  63194. */
  63195. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63196. _this._rotationY = 0;
  63197. /** @hidden */
  63198. _this._prefiltered = false;
  63199. _this.name = rootUrl;
  63200. _this.url = rootUrl;
  63201. _this._noMipmap = noMipmap;
  63202. _this.hasAlpha = false;
  63203. _this._format = format;
  63204. _this.isCube = true;
  63205. _this._textureMatrix = BABYLON.Matrix.Identity();
  63206. _this._createPolynomials = createPolynomials;
  63207. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63208. if (!rootUrl && !files) {
  63209. return _this;
  63210. }
  63211. var lastDot = rootUrl.lastIndexOf(".");
  63212. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63213. var isDDS = (extension === ".dds");
  63214. var isEnv = (extension === ".env");
  63215. if (isEnv) {
  63216. _this.gammaSpace = false;
  63217. _this._prefiltered = false;
  63218. }
  63219. else {
  63220. _this._prefiltered = prefiltered;
  63221. if (prefiltered) {
  63222. _this.gammaSpace = false;
  63223. }
  63224. }
  63225. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63226. if (!files) {
  63227. if (!isEnv && !isDDS && !extensions) {
  63228. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63229. }
  63230. files = [];
  63231. if (extensions) {
  63232. for (var index = 0; index < extensions.length; index++) {
  63233. files.push(rootUrl + extensions[index]);
  63234. }
  63235. }
  63236. }
  63237. _this._files = files;
  63238. if (!_this._texture) {
  63239. if (!scene.useDelayedTextureLoading) {
  63240. if (prefiltered) {
  63241. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63242. }
  63243. else {
  63244. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63245. }
  63246. }
  63247. else {
  63248. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63249. }
  63250. }
  63251. else if (onLoad) {
  63252. if (_this._texture.isReady) {
  63253. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63254. }
  63255. else {
  63256. _this._texture.onLoadedObservable.add(onLoad);
  63257. }
  63258. }
  63259. return _this;
  63260. }
  63261. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63262. get: function () {
  63263. return this._boundingBoxSize;
  63264. },
  63265. /**
  63266. * Gets or sets the size of the bounding box associated with the cube texture
  63267. * When defined, the cubemap will switch to local mode
  63268. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63269. * @example https://www.babylonjs-playground.com/#RNASML
  63270. */
  63271. set: function (value) {
  63272. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63273. return;
  63274. }
  63275. this._boundingBoxSize = value;
  63276. var scene = this.getScene();
  63277. if (scene) {
  63278. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63279. }
  63280. },
  63281. enumerable: true,
  63282. configurable: true
  63283. });
  63284. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63285. /**
  63286. * Gets texture matrix rotation angle around Y axis radians.
  63287. */
  63288. get: function () {
  63289. return this._rotationY;
  63290. },
  63291. /**
  63292. * Sets texture matrix rotation angle around Y axis in radians.
  63293. */
  63294. set: function (value) {
  63295. this._rotationY = value;
  63296. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63297. },
  63298. enumerable: true,
  63299. configurable: true
  63300. });
  63301. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63302. var rootUrlKey = "";
  63303. files.forEach(function (url) { return rootUrlKey += url; });
  63304. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63305. };
  63306. /**
  63307. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63308. * @param url defines the url of the prefiltered texture
  63309. * @param scene defines the scene the texture is attached to
  63310. * @param forcedExtension defines the extension of the file if different from the url
  63311. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63312. * @return the prefiltered texture
  63313. */
  63314. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63315. if (forcedExtension === void 0) { forcedExtension = null; }
  63316. if (createPolynomials === void 0) { createPolynomials = true; }
  63317. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63318. };
  63319. // Methods
  63320. CubeTexture.prototype.delayLoad = function () {
  63321. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63322. return;
  63323. }
  63324. var scene = this.getScene();
  63325. if (!scene) {
  63326. return;
  63327. }
  63328. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63329. this._texture = this._getFromCache(this.url, this._noMipmap);
  63330. if (!this._texture) {
  63331. if (this._prefiltered) {
  63332. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63333. }
  63334. else {
  63335. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63336. }
  63337. }
  63338. };
  63339. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63340. return this._textureMatrix;
  63341. };
  63342. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63343. this._textureMatrix = value;
  63344. };
  63345. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63346. var texture = BABYLON.SerializationHelper.Parse(function () {
  63347. var prefiltered = false;
  63348. if (parsedTexture.prefiltered) {
  63349. prefiltered = parsedTexture.prefiltered;
  63350. }
  63351. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63352. }, parsedTexture, scene);
  63353. // Local Cubemaps
  63354. if (parsedTexture.boundingBoxPosition) {
  63355. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63356. }
  63357. if (parsedTexture.boundingBoxSize) {
  63358. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63359. }
  63360. // Animations
  63361. if (parsedTexture.animations) {
  63362. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63363. var parsedAnimation = parsedTexture.animations[animationIndex];
  63364. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63365. }
  63366. }
  63367. return texture;
  63368. };
  63369. CubeTexture.prototype.clone = function () {
  63370. var _this = this;
  63371. return BABYLON.SerializationHelper.Clone(function () {
  63372. var scene = _this.getScene();
  63373. if (!scene) {
  63374. return _this;
  63375. }
  63376. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63377. }, this);
  63378. };
  63379. __decorate([
  63380. BABYLON.serialize("rotationY")
  63381. ], CubeTexture.prototype, "_rotationY", void 0);
  63382. return CubeTexture;
  63383. }(BABYLON.BaseTexture));
  63384. BABYLON.CubeTexture = CubeTexture;
  63385. })(BABYLON || (BABYLON = {}));
  63386. //# sourceMappingURL=babylon.cubeTexture.js.map
  63387. var BABYLON;
  63388. (function (BABYLON) {
  63389. /**
  63390. * Raw cube texture where the raw buffers are passed in
  63391. */
  63392. var RawCubeTexture = /** @class */ (function (_super) {
  63393. __extends(RawCubeTexture, _super);
  63394. /**
  63395. * Creates a cube texture where the raw buffers are passed in.
  63396. * @param scene defines the scene the texture is attached to
  63397. * @param data defines the array of data to use to create each face
  63398. * @param size defines the size of the textures
  63399. * @param format defines the format of the data
  63400. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63401. * @param generateMipMaps defines if the engine should generate the mip levels
  63402. * @param invertY defines if data must be stored with Y axis inverted
  63403. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63404. * @param compression defines the compression used (null by default)
  63405. */
  63406. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63407. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63408. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63409. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63410. if (invertY === void 0) { invertY = false; }
  63411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63412. if (compression === void 0) { compression = null; }
  63413. var _this = _super.call(this, "", scene) || this;
  63414. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63415. return _this;
  63416. }
  63417. /**
  63418. * Updates the raw cube texture.
  63419. * @param data defines the data to store
  63420. * @param format defines the data format
  63421. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63422. * @param invertY defines if data must be stored with Y axis inverted
  63423. * @param compression defines the compression used (null by default)
  63424. * @param level defines which level of the texture to update
  63425. */
  63426. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63427. if (compression === void 0) { compression = null; }
  63428. if (level === void 0) { level = 0; }
  63429. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63430. };
  63431. /**
  63432. * Updates a raw cube texture with RGBD encoded data.
  63433. * @param data defines the array of data [mipmap][face] to use to create each face
  63434. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63435. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63436. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63437. * @returns a promsie that resolves when the operation is complete
  63438. */
  63439. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63440. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63441. if (lodScale === void 0) { lodScale = 0.8; }
  63442. if (lodOffset === void 0) { lodOffset = 0; }
  63443. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63444. };
  63445. /**
  63446. * Clones the raw cube texture.
  63447. * @return a new cube texture
  63448. */
  63449. RawCubeTexture.prototype.clone = function () {
  63450. var _this = this;
  63451. return BABYLON.SerializationHelper.Clone(function () {
  63452. var scene = _this.getScene();
  63453. var internalTexture = _this._texture;
  63454. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63455. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63456. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63457. }
  63458. return texture;
  63459. }, this);
  63460. };
  63461. /** @hidden */
  63462. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63463. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63464. internalTexture._bufferViewArrayArray = data;
  63465. internalTexture._lodGenerationScale = lodScale;
  63466. internalTexture._lodGenerationOffset = lodOffset;
  63467. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63468. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63469. internalTexture.isReady = true;
  63470. });
  63471. };
  63472. return RawCubeTexture;
  63473. }(BABYLON.CubeTexture));
  63474. BABYLON.RawCubeTexture = RawCubeTexture;
  63475. })(BABYLON || (BABYLON = {}));
  63476. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63477. var BABYLON;
  63478. (function (BABYLON) {
  63479. var RenderTargetTexture = /** @class */ (function (_super) {
  63480. __extends(RenderTargetTexture, _super);
  63481. /**
  63482. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63483. * or used a shadow, depth texture...
  63484. * @param name The friendly name of the texture
  63485. * @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)
  63486. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63487. * @param generateMipMaps True if mip maps need to be generated after render.
  63488. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63489. * @param type The type of the buffer in the RTT (int, half float, float...)
  63490. * @param isCube True if a cube texture needs to be created
  63491. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63492. * @param generateDepthBuffer True to generate a depth buffer
  63493. * @param generateStencilBuffer True to generate a stencil buffer
  63494. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63495. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63496. */
  63497. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63498. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63499. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63500. if (isCube === void 0) { isCube = false; }
  63501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63502. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63503. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63504. if (isMulti === void 0) { isMulti = false; }
  63505. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63506. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63507. _this.isCube = isCube;
  63508. /**
  63509. * Use this list to define the list of mesh you want to render.
  63510. */
  63511. _this.renderList = new Array();
  63512. _this.renderParticles = true;
  63513. _this.renderSprites = false;
  63514. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63515. _this.ignoreCameraViewport = false;
  63516. // Events
  63517. /**
  63518. * An event triggered when the texture is unbind.
  63519. */
  63520. _this.onBeforeBindObservable = new BABYLON.Observable();
  63521. /**
  63522. * An event triggered when the texture is unbind.
  63523. */
  63524. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63525. /**
  63526. * An event triggered before rendering the texture
  63527. */
  63528. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63529. /**
  63530. * An event triggered after rendering the texture
  63531. */
  63532. _this.onAfterRenderObservable = new BABYLON.Observable();
  63533. /**
  63534. * An event triggered after the texture clear
  63535. */
  63536. _this.onClearObservable = new BABYLON.Observable();
  63537. _this._currentRefreshId = -1;
  63538. _this._refreshRate = 1;
  63539. _this._samples = 1;
  63540. /**
  63541. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63542. * It must define where the camera used to render the texture is set
  63543. */
  63544. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63545. scene = _this.getScene();
  63546. if (!scene) {
  63547. return _this;
  63548. }
  63549. _this._engine = scene.getEngine();
  63550. _this.name = name;
  63551. _this.isRenderTarget = true;
  63552. _this._initialSizeParameter = size;
  63553. _this._processSizeParameter(size);
  63554. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63555. });
  63556. _this._generateMipMaps = generateMipMaps ? true : false;
  63557. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63558. // Rendering groups
  63559. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63560. if (isMulti) {
  63561. return _this;
  63562. }
  63563. _this._renderTargetOptions = {
  63564. generateMipMaps: generateMipMaps,
  63565. type: type,
  63566. format: format,
  63567. samplingMode: samplingMode,
  63568. generateDepthBuffer: generateDepthBuffer,
  63569. generateStencilBuffer: generateStencilBuffer
  63570. };
  63571. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63572. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63573. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63574. }
  63575. if (isCube) {
  63576. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63577. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63578. _this._textureMatrix = BABYLON.Matrix.Identity();
  63579. }
  63580. else {
  63581. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63582. }
  63583. return _this;
  63584. }
  63585. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63586. get: function () {
  63587. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63593. get: function () {
  63594. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63595. },
  63596. enumerable: true,
  63597. configurable: true
  63598. });
  63599. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63600. get: function () {
  63601. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63607. set: function (callback) {
  63608. if (this._onAfterUnbindObserver) {
  63609. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63610. }
  63611. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63612. },
  63613. enumerable: true,
  63614. configurable: true
  63615. });
  63616. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63617. set: function (callback) {
  63618. if (this._onBeforeRenderObserver) {
  63619. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63620. }
  63621. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63622. },
  63623. enumerable: true,
  63624. configurable: true
  63625. });
  63626. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63627. set: function (callback) {
  63628. if (this._onAfterRenderObserver) {
  63629. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63630. }
  63631. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63632. },
  63633. enumerable: true,
  63634. configurable: true
  63635. });
  63636. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63637. set: function (callback) {
  63638. if (this._onClearObserver) {
  63639. this.onClearObservable.remove(this._onClearObserver);
  63640. }
  63641. this._onClearObserver = this.onClearObservable.add(callback);
  63642. },
  63643. enumerable: true,
  63644. configurable: true
  63645. });
  63646. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63647. get: function () {
  63648. return this._renderTargetOptions;
  63649. },
  63650. enumerable: true,
  63651. configurable: true
  63652. });
  63653. RenderTargetTexture.prototype._onRatioRescale = function () {
  63654. if (this._sizeRatio) {
  63655. this.resize(this._initialSizeParameter);
  63656. }
  63657. };
  63658. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63659. get: function () {
  63660. return this._boundingBoxSize;
  63661. },
  63662. /**
  63663. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63664. * When defined, the cubemap will switch to local mode
  63665. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63666. * @example https://www.babylonjs-playground.com/#RNASML
  63667. */
  63668. set: function (value) {
  63669. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63670. return;
  63671. }
  63672. this._boundingBoxSize = value;
  63673. var scene = this.getScene();
  63674. if (scene) {
  63675. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63676. }
  63677. },
  63678. enumerable: true,
  63679. configurable: true
  63680. });
  63681. /**
  63682. * Creates a depth stencil texture.
  63683. * This is only available in WebGL 2 or with the depth texture extension available.
  63684. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63685. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63686. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63687. */
  63688. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63689. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63690. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63691. if (generateStencil === void 0) { generateStencil = false; }
  63692. if (!this.getScene()) {
  63693. return;
  63694. }
  63695. var engine = this.getScene().getEngine();
  63696. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63697. bilinearFiltering: bilinearFiltering,
  63698. comparisonFunction: comparisonFunction,
  63699. generateStencil: generateStencil,
  63700. isCube: this.isCube
  63701. });
  63702. engine.setFrameBufferDepthStencilTexture(this);
  63703. };
  63704. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63705. if (size.ratio) {
  63706. this._sizeRatio = size.ratio;
  63707. this._size = {
  63708. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63709. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63710. };
  63711. }
  63712. else {
  63713. this._size = size;
  63714. }
  63715. };
  63716. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63717. get: function () {
  63718. return this._samples;
  63719. },
  63720. set: function (value) {
  63721. if (this._samples === value) {
  63722. return;
  63723. }
  63724. var scene = this.getScene();
  63725. if (!scene) {
  63726. return;
  63727. }
  63728. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63729. },
  63730. enumerable: true,
  63731. configurable: true
  63732. });
  63733. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63734. this._currentRefreshId = -1;
  63735. };
  63736. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63737. get: function () {
  63738. return this._refreshRate;
  63739. },
  63740. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63741. set: function (value) {
  63742. this._refreshRate = value;
  63743. this.resetRefreshCounter();
  63744. },
  63745. enumerable: true,
  63746. configurable: true
  63747. });
  63748. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63749. if (!this._postProcessManager) {
  63750. var scene = this.getScene();
  63751. if (!scene) {
  63752. return;
  63753. }
  63754. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63755. this._postProcesses = new Array();
  63756. }
  63757. this._postProcesses.push(postProcess);
  63758. this._postProcesses[0].autoClear = false;
  63759. };
  63760. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63761. if (!this._postProcesses) {
  63762. return;
  63763. }
  63764. if (dispose) {
  63765. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63766. var postProcess = _a[_i];
  63767. postProcess.dispose();
  63768. }
  63769. }
  63770. this._postProcesses = [];
  63771. };
  63772. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63773. if (!this._postProcesses) {
  63774. return;
  63775. }
  63776. var index = this._postProcesses.indexOf(postProcess);
  63777. if (index === -1) {
  63778. return;
  63779. }
  63780. this._postProcesses.splice(index, 1);
  63781. if (this._postProcesses.length > 0) {
  63782. this._postProcesses[0].autoClear = false;
  63783. }
  63784. };
  63785. RenderTargetTexture.prototype._shouldRender = function () {
  63786. if (this._currentRefreshId === -1) { // At least render once
  63787. this._currentRefreshId = 1;
  63788. return true;
  63789. }
  63790. if (this.refreshRate === this._currentRefreshId) {
  63791. this._currentRefreshId = 1;
  63792. return true;
  63793. }
  63794. this._currentRefreshId++;
  63795. return false;
  63796. };
  63797. RenderTargetTexture.prototype.getRenderSize = function () {
  63798. if (this._size.width) {
  63799. return this._size.width;
  63800. }
  63801. return this._size;
  63802. };
  63803. RenderTargetTexture.prototype.getRenderWidth = function () {
  63804. if (this._size.width) {
  63805. return this._size.width;
  63806. }
  63807. return this._size;
  63808. };
  63809. RenderTargetTexture.prototype.getRenderHeight = function () {
  63810. if (this._size.width) {
  63811. return this._size.height;
  63812. }
  63813. return this._size;
  63814. };
  63815. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63816. get: function () {
  63817. return true;
  63818. },
  63819. enumerable: true,
  63820. configurable: true
  63821. });
  63822. RenderTargetTexture.prototype.scale = function (ratio) {
  63823. var newSize = this.getRenderSize() * ratio;
  63824. this.resize(newSize);
  63825. };
  63826. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63827. if (this.isCube) {
  63828. return this._textureMatrix;
  63829. }
  63830. return _super.prototype.getReflectionTextureMatrix.call(this);
  63831. };
  63832. RenderTargetTexture.prototype.resize = function (size) {
  63833. this.releaseInternalTexture();
  63834. var scene = this.getScene();
  63835. if (!scene) {
  63836. return;
  63837. }
  63838. this._processSizeParameter(size);
  63839. if (this.isCube) {
  63840. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63841. }
  63842. else {
  63843. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63844. }
  63845. };
  63846. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63847. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63848. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63849. var scene = this.getScene();
  63850. if (!scene) {
  63851. return;
  63852. }
  63853. var engine = scene.getEngine();
  63854. if (this.useCameraPostProcesses !== undefined) {
  63855. useCameraPostProcess = this.useCameraPostProcesses;
  63856. }
  63857. if (this._waitingRenderList) {
  63858. this.renderList = [];
  63859. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63860. var id = this._waitingRenderList[index];
  63861. var mesh_1 = scene.getMeshByID(id);
  63862. if (mesh_1) {
  63863. this.renderList.push(mesh_1);
  63864. }
  63865. }
  63866. delete this._waitingRenderList;
  63867. }
  63868. // Is predicate defined?
  63869. if (this.renderListPredicate) {
  63870. if (this.renderList) {
  63871. this.renderList.splice(0); // Clear previous renderList
  63872. }
  63873. else {
  63874. this.renderList = [];
  63875. }
  63876. var scene = this.getScene();
  63877. if (!scene) {
  63878. return;
  63879. }
  63880. var sceneMeshes = scene.meshes;
  63881. for (var index = 0; index < sceneMeshes.length; index++) {
  63882. var mesh = sceneMeshes[index];
  63883. if (this.renderListPredicate(mesh)) {
  63884. this.renderList.push(mesh);
  63885. }
  63886. }
  63887. }
  63888. this.onBeforeBindObservable.notifyObservers(this);
  63889. // Set custom projection.
  63890. // Needs to be before binding to prevent changing the aspect ratio.
  63891. var camera;
  63892. if (this.activeCamera) {
  63893. camera = this.activeCamera;
  63894. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63895. if (this.activeCamera !== scene.activeCamera) {
  63896. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63897. }
  63898. }
  63899. else {
  63900. camera = scene.activeCamera;
  63901. if (camera) {
  63902. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63903. }
  63904. }
  63905. // Prepare renderingManager
  63906. this._renderingManager.reset();
  63907. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63908. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63909. var sceneRenderId = scene.getRenderId();
  63910. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63911. var mesh = currentRenderList[meshIndex];
  63912. if (mesh) {
  63913. if (!mesh.isReady(this.refreshRate === 0)) {
  63914. this.resetRefreshCounter();
  63915. continue;
  63916. }
  63917. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63918. var isMasked = void 0;
  63919. if (!this.renderList && camera) {
  63920. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63921. }
  63922. else {
  63923. isMasked = false;
  63924. }
  63925. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63926. mesh._activate(sceneRenderId);
  63927. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63928. var subMesh = mesh.subMeshes[subIndex];
  63929. scene._activeIndices.addCount(subMesh.indexCount, false);
  63930. this._renderingManager.dispatch(subMesh, mesh);
  63931. }
  63932. }
  63933. }
  63934. }
  63935. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63936. var particleSystem = scene.particleSystems[particleIndex];
  63937. var emitter = particleSystem.emitter;
  63938. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63939. continue;
  63940. }
  63941. if (currentRenderList.indexOf(emitter) >= 0) {
  63942. this._renderingManager.dispatchParticles(particleSystem);
  63943. }
  63944. }
  63945. if (this.isCube) {
  63946. for (var face = 0; face < 6; face++) {
  63947. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63948. scene.incrementRenderId();
  63949. scene.resetCachedMaterial();
  63950. }
  63951. }
  63952. else {
  63953. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63954. }
  63955. this.onAfterUnbindObservable.notifyObservers(this);
  63956. if (scene.activeCamera) {
  63957. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63958. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63959. }
  63960. engine.setViewport(scene.activeCamera.viewport);
  63961. }
  63962. scene.resetCachedMaterial();
  63963. };
  63964. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63965. var minimum = 128;
  63966. var x = renderDimension * scale;
  63967. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63968. // Ensure we don't exceed the render dimension (while staying POT)
  63969. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63970. };
  63971. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63972. var _this = this;
  63973. if (!this._texture) {
  63974. return;
  63975. }
  63976. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63977. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63978. });
  63979. };
  63980. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63981. var scene = this.getScene();
  63982. if (!scene) {
  63983. return;
  63984. }
  63985. var engine = scene.getEngine();
  63986. if (!this._texture) {
  63987. return;
  63988. }
  63989. // Bind
  63990. if (this._postProcessManager) {
  63991. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63992. }
  63993. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63994. if (this._texture) {
  63995. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63996. }
  63997. }
  63998. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63999. // Clear
  64000. if (this.onClearObservable.hasObservers()) {
  64001. this.onClearObservable.notifyObservers(engine);
  64002. }
  64003. else {
  64004. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64005. }
  64006. if (!this._doNotChangeAspectRatio) {
  64007. scene.updateTransformMatrix(true);
  64008. }
  64009. // Render
  64010. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64011. if (this._postProcessManager) {
  64012. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64013. }
  64014. else if (useCameraPostProcess) {
  64015. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64016. }
  64017. if (!this._doNotChangeAspectRatio) {
  64018. scene.updateTransformMatrix(true);
  64019. }
  64020. // Dump ?
  64021. if (dumpForDebug) {
  64022. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64023. }
  64024. // Unbind
  64025. if (!this.isCube || faceIndex === 5) {
  64026. if (this.isCube) {
  64027. if (faceIndex === 5) {
  64028. engine.generateMipMapsForCubemap(this._texture);
  64029. }
  64030. }
  64031. this.unbindFrameBuffer(engine, faceIndex);
  64032. }
  64033. else {
  64034. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64035. }
  64036. };
  64037. /**
  64038. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64039. * This allowed control for front to back rendering or reversly depending of the special needs.
  64040. *
  64041. * @param renderingGroupId The rendering group id corresponding to its index
  64042. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64043. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64044. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64045. */
  64046. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64047. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64048. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64049. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64050. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64051. };
  64052. /**
  64053. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64054. *
  64055. * @param renderingGroupId The rendering group id corresponding to its index
  64056. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64057. */
  64058. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64059. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64060. };
  64061. RenderTargetTexture.prototype.clone = function () {
  64062. var textureSize = this.getSize();
  64063. 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);
  64064. // Base texture
  64065. newTexture.hasAlpha = this.hasAlpha;
  64066. newTexture.level = this.level;
  64067. // RenderTarget Texture
  64068. newTexture.coordinatesMode = this.coordinatesMode;
  64069. if (this.renderList) {
  64070. newTexture.renderList = this.renderList.slice(0);
  64071. }
  64072. return newTexture;
  64073. };
  64074. RenderTargetTexture.prototype.serialize = function () {
  64075. if (!this.name) {
  64076. return null;
  64077. }
  64078. var serializationObject = _super.prototype.serialize.call(this);
  64079. serializationObject.renderTargetSize = this.getRenderSize();
  64080. serializationObject.renderList = [];
  64081. if (this.renderList) {
  64082. for (var index = 0; index < this.renderList.length; index++) {
  64083. serializationObject.renderList.push(this.renderList[index].id);
  64084. }
  64085. }
  64086. return serializationObject;
  64087. };
  64088. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64089. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64090. var objBuffer = this.getInternalTexture();
  64091. var scene = this.getScene();
  64092. if (objBuffer && scene) {
  64093. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64094. }
  64095. };
  64096. RenderTargetTexture.prototype.dispose = function () {
  64097. if (this._postProcessManager) {
  64098. this._postProcessManager.dispose();
  64099. this._postProcessManager = null;
  64100. }
  64101. this.clearPostProcesses(true);
  64102. if (this._resizeObserver) {
  64103. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64104. this._resizeObserver = null;
  64105. }
  64106. this.renderList = null;
  64107. // Remove from custom render targets
  64108. var scene = this.getScene();
  64109. if (!scene) {
  64110. return;
  64111. }
  64112. var index = scene.customRenderTargets.indexOf(this);
  64113. if (index >= 0) {
  64114. scene.customRenderTargets.splice(index, 1);
  64115. }
  64116. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64117. var camera = _a[_i];
  64118. index = camera.customRenderTargets.indexOf(this);
  64119. if (index >= 0) {
  64120. camera.customRenderTargets.splice(index, 1);
  64121. }
  64122. }
  64123. _super.prototype.dispose.call(this);
  64124. };
  64125. RenderTargetTexture.prototype._rebuild = function () {
  64126. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64127. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64128. }
  64129. if (this._postProcessManager) {
  64130. this._postProcessManager._rebuild();
  64131. }
  64132. };
  64133. /**
  64134. * Clear the info related to rendering groups preventing retention point in material dispose.
  64135. */
  64136. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64137. if (this._renderingManager) {
  64138. this._renderingManager.freeRenderingGroups();
  64139. }
  64140. };
  64141. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64142. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64143. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64144. return RenderTargetTexture;
  64145. }(BABYLON.Texture));
  64146. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64147. })(BABYLON || (BABYLON = {}));
  64148. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64149. var BABYLON;
  64150. (function (BABYLON) {
  64151. ;
  64152. var MultiRenderTarget = /** @class */ (function (_super) {
  64153. __extends(MultiRenderTarget, _super);
  64154. function MultiRenderTarget(name, size, count, scene, options) {
  64155. var _this = this;
  64156. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64157. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64158. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64159. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64160. _this._engine = scene.getEngine();
  64161. if (!_this.isSupported) {
  64162. _this.dispose();
  64163. return;
  64164. }
  64165. var types = [];
  64166. var samplingModes = [];
  64167. for (var i = 0; i < count; i++) {
  64168. if (options && options.types && options.types[i] !== undefined) {
  64169. types.push(options.types[i]);
  64170. }
  64171. else {
  64172. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64173. }
  64174. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64175. samplingModes.push(options.samplingModes[i]);
  64176. }
  64177. else {
  64178. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64179. }
  64180. }
  64181. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64182. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64183. _this._size = size;
  64184. _this._multiRenderTargetOptions = {
  64185. samplingModes: samplingModes,
  64186. generateMipMaps: generateMipMaps,
  64187. generateDepthBuffer: generateDepthBuffer,
  64188. generateStencilBuffer: generateStencilBuffer,
  64189. generateDepthTexture: generateDepthTexture,
  64190. types: types,
  64191. textureCount: count
  64192. };
  64193. _this._createInternalTextures();
  64194. _this._createTextures();
  64195. return _this;
  64196. }
  64197. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64198. get: function () {
  64199. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64200. },
  64201. enumerable: true,
  64202. configurable: true
  64203. });
  64204. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64205. get: function () {
  64206. return this._textures;
  64207. },
  64208. enumerable: true,
  64209. configurable: true
  64210. });
  64211. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64212. get: function () {
  64213. return this._textures[this._textures.length - 1];
  64214. },
  64215. enumerable: true,
  64216. configurable: true
  64217. });
  64218. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64219. set: function (wrap) {
  64220. if (this._textures) {
  64221. for (var i = 0; i < this._textures.length; i++) {
  64222. this._textures[i].wrapU = wrap;
  64223. }
  64224. }
  64225. },
  64226. enumerable: true,
  64227. configurable: true
  64228. });
  64229. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64230. set: function (wrap) {
  64231. if (this._textures) {
  64232. for (var i = 0; i < this._textures.length; i++) {
  64233. this._textures[i].wrapV = wrap;
  64234. }
  64235. }
  64236. },
  64237. enumerable: true,
  64238. configurable: true
  64239. });
  64240. MultiRenderTarget.prototype._rebuild = function () {
  64241. this.releaseInternalTextures();
  64242. this._createInternalTextures();
  64243. for (var i = 0; i < this._internalTextures.length; i++) {
  64244. var texture = this._textures[i];
  64245. texture._texture = this._internalTextures[i];
  64246. }
  64247. // Keeps references to frame buffer and stencil/depth buffer
  64248. this._texture = this._internalTextures[0];
  64249. };
  64250. MultiRenderTarget.prototype._createInternalTextures = function () {
  64251. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64252. };
  64253. MultiRenderTarget.prototype._createTextures = function () {
  64254. this._textures = [];
  64255. for (var i = 0; i < this._internalTextures.length; i++) {
  64256. var texture = new BABYLON.Texture(null, this.getScene());
  64257. texture._texture = this._internalTextures[i];
  64258. this._textures.push(texture);
  64259. }
  64260. // Keeps references to frame buffer and stencil/depth buffer
  64261. this._texture = this._internalTextures[0];
  64262. };
  64263. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64264. get: function () {
  64265. return this._samples;
  64266. },
  64267. set: function (value) {
  64268. if (this._samples === value) {
  64269. return;
  64270. }
  64271. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64272. },
  64273. enumerable: true,
  64274. configurable: true
  64275. });
  64276. MultiRenderTarget.prototype.resize = function (size) {
  64277. this.releaseInternalTextures();
  64278. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64279. this._createInternalTextures();
  64280. };
  64281. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64282. var _this = this;
  64283. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64284. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64285. });
  64286. };
  64287. MultiRenderTarget.prototype.dispose = function () {
  64288. this.releaseInternalTextures();
  64289. _super.prototype.dispose.call(this);
  64290. };
  64291. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64292. if (!this._internalTextures) {
  64293. return;
  64294. }
  64295. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64296. if (this._internalTextures[i] !== undefined) {
  64297. this._internalTextures[i].dispose();
  64298. this._internalTextures.splice(i, 1);
  64299. }
  64300. }
  64301. };
  64302. return MultiRenderTarget;
  64303. }(BABYLON.RenderTargetTexture));
  64304. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64305. })(BABYLON || (BABYLON = {}));
  64306. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64307. var BABYLON;
  64308. (function (BABYLON) {
  64309. var MirrorTexture = /** @class */ (function (_super) {
  64310. __extends(MirrorTexture, _super);
  64311. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64312. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64314. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64315. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64316. _this.scene = scene;
  64317. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64318. _this._transformMatrix = BABYLON.Matrix.Zero();
  64319. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64320. _this._adaptiveBlurKernel = 0;
  64321. _this._blurKernelX = 0;
  64322. _this._blurKernelY = 0;
  64323. _this._blurRatio = 1.0;
  64324. _this.ignoreCameraViewport = true;
  64325. _this._updateGammaSpace();
  64326. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64327. _this._updateGammaSpace;
  64328. });
  64329. _this.onBeforeRenderObservable.add(function () {
  64330. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64331. _this._savedViewMatrix = scene.getViewMatrix();
  64332. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64333. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64334. scene.clipPlane = _this.mirrorPlane;
  64335. scene.getEngine().cullBackFaces = false;
  64336. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64337. });
  64338. _this.onAfterRenderObservable.add(function () {
  64339. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64340. scene.getEngine().cullBackFaces = true;
  64341. scene._mirroredCameraPosition = null;
  64342. delete scene.clipPlane;
  64343. });
  64344. return _this;
  64345. }
  64346. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64347. get: function () {
  64348. return this._blurRatio;
  64349. },
  64350. set: function (value) {
  64351. if (this._blurRatio === value) {
  64352. return;
  64353. }
  64354. this._blurRatio = value;
  64355. this._preparePostProcesses();
  64356. },
  64357. enumerable: true,
  64358. configurable: true
  64359. });
  64360. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64361. set: function (value) {
  64362. this._adaptiveBlurKernel = value;
  64363. this._autoComputeBlurKernel();
  64364. },
  64365. enumerable: true,
  64366. configurable: true
  64367. });
  64368. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64369. set: function (value) {
  64370. this.blurKernelX = value;
  64371. this.blurKernelY = value;
  64372. },
  64373. enumerable: true,
  64374. configurable: true
  64375. });
  64376. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64377. get: function () {
  64378. return this._blurKernelX;
  64379. },
  64380. set: function (value) {
  64381. if (this._blurKernelX === value) {
  64382. return;
  64383. }
  64384. this._blurKernelX = value;
  64385. this._preparePostProcesses();
  64386. },
  64387. enumerable: true,
  64388. configurable: true
  64389. });
  64390. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64391. get: function () {
  64392. return this._blurKernelY;
  64393. },
  64394. set: function (value) {
  64395. if (this._blurKernelY === value) {
  64396. return;
  64397. }
  64398. this._blurKernelY = value;
  64399. this._preparePostProcesses();
  64400. },
  64401. enumerable: true,
  64402. configurable: true
  64403. });
  64404. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64405. var engine = this.getScene().getEngine();
  64406. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64407. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64408. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64409. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64410. };
  64411. MirrorTexture.prototype._onRatioRescale = function () {
  64412. if (this._sizeRatio) {
  64413. this.resize(this._initialSizeParameter);
  64414. if (!this._adaptiveBlurKernel) {
  64415. this._preparePostProcesses();
  64416. }
  64417. }
  64418. if (this._adaptiveBlurKernel) {
  64419. this._autoComputeBlurKernel();
  64420. }
  64421. };
  64422. MirrorTexture.prototype._updateGammaSpace = function () {
  64423. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64424. };
  64425. MirrorTexture.prototype._preparePostProcesses = function () {
  64426. this.clearPostProcesses(true);
  64427. if (this._blurKernelX && this._blurKernelY) {
  64428. var engine = this.getScene().getEngine();
  64429. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64430. 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);
  64431. this._blurX.autoClear = false;
  64432. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64433. this._blurX.inputTexture = this._texture;
  64434. }
  64435. else {
  64436. this._blurX.alwaysForcePOT = true;
  64437. }
  64438. 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);
  64439. this._blurY.autoClear = false;
  64440. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64441. this.addPostProcess(this._blurX);
  64442. this.addPostProcess(this._blurY);
  64443. }
  64444. else {
  64445. if (this._blurY) {
  64446. this.removePostProcess(this._blurY);
  64447. this._blurY.dispose();
  64448. this._blurY = null;
  64449. }
  64450. if (this._blurX) {
  64451. this.removePostProcess(this._blurX);
  64452. this._blurX.dispose();
  64453. this._blurX = null;
  64454. }
  64455. }
  64456. };
  64457. MirrorTexture.prototype.clone = function () {
  64458. var scene = this.getScene();
  64459. if (!scene) {
  64460. return this;
  64461. }
  64462. var textureSize = this.getSize();
  64463. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64464. // Base texture
  64465. newTexture.hasAlpha = this.hasAlpha;
  64466. newTexture.level = this.level;
  64467. // Mirror Texture
  64468. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64469. if (this.renderList) {
  64470. newTexture.renderList = this.renderList.slice(0);
  64471. }
  64472. return newTexture;
  64473. };
  64474. MirrorTexture.prototype.serialize = function () {
  64475. if (!this.name) {
  64476. return null;
  64477. }
  64478. var serializationObject = _super.prototype.serialize.call(this);
  64479. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64480. return serializationObject;
  64481. };
  64482. MirrorTexture.prototype.dispose = function () {
  64483. _super.prototype.dispose.call(this);
  64484. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64485. };
  64486. return MirrorTexture;
  64487. }(BABYLON.RenderTargetTexture));
  64488. BABYLON.MirrorTexture = MirrorTexture;
  64489. })(BABYLON || (BABYLON = {}));
  64490. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64491. var BABYLON;
  64492. (function (BABYLON) {
  64493. /**
  64494. * Creates a refraction texture used by refraction channel of the standard material.
  64495. * @param name the texture name
  64496. * @param size size of the underlying texture
  64497. * @param scene root scene
  64498. */
  64499. var RefractionTexture = /** @class */ (function (_super) {
  64500. __extends(RefractionTexture, _super);
  64501. function RefractionTexture(name, size, scene, generateMipMaps) {
  64502. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64503. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64504. _this.depth = 2.0;
  64505. _this.onBeforeRenderObservable.add(function () {
  64506. scene.clipPlane = _this.refractionPlane;
  64507. });
  64508. _this.onAfterRenderObservable.add(function () {
  64509. delete scene.clipPlane;
  64510. });
  64511. return _this;
  64512. }
  64513. RefractionTexture.prototype.clone = function () {
  64514. var scene = this.getScene();
  64515. if (!scene) {
  64516. return this;
  64517. }
  64518. var textureSize = this.getSize();
  64519. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64520. // Base texture
  64521. newTexture.hasAlpha = this.hasAlpha;
  64522. newTexture.level = this.level;
  64523. // Refraction Texture
  64524. newTexture.refractionPlane = this.refractionPlane.clone();
  64525. if (this.renderList) {
  64526. newTexture.renderList = this.renderList.slice(0);
  64527. }
  64528. newTexture.depth = this.depth;
  64529. return newTexture;
  64530. };
  64531. RefractionTexture.prototype.serialize = function () {
  64532. if (!this.name) {
  64533. return null;
  64534. }
  64535. var serializationObject = _super.prototype.serialize.call(this);
  64536. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64537. serializationObject.depth = this.depth;
  64538. return serializationObject;
  64539. };
  64540. return RefractionTexture;
  64541. }(BABYLON.RenderTargetTexture));
  64542. BABYLON.RefractionTexture = RefractionTexture;
  64543. })(BABYLON || (BABYLON = {}));
  64544. //# sourceMappingURL=babylon.refractionTexture.js.map
  64545. var BABYLON;
  64546. (function (BABYLON) {
  64547. /**
  64548. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64549. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64550. */
  64551. var DynamicTexture = /** @class */ (function (_super) {
  64552. __extends(DynamicTexture, _super);
  64553. /**
  64554. * Creates a {BABYLON.DynamicTexture}
  64555. * @param name defines the name of the texture
  64556. * @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
  64557. * @param scene defines the scene where you want the texture
  64558. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64559. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64560. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64561. */
  64562. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64563. if (scene === void 0) { scene = null; }
  64564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64565. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64566. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64567. _this.name = name;
  64568. _this._engine = _this.getScene().getEngine();
  64569. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64570. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64571. _this._generateMipMaps = generateMipMaps;
  64572. if (options.getContext) {
  64573. _this._canvas = options;
  64574. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64575. }
  64576. else {
  64577. _this._canvas = document.createElement("canvas");
  64578. if (options.width || options.width === 0) {
  64579. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64580. }
  64581. else {
  64582. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64583. }
  64584. }
  64585. var textureSize = _this.getSize();
  64586. _this._canvas.width = textureSize.width;
  64587. _this._canvas.height = textureSize.height;
  64588. _this._context = _this._canvas.getContext("2d");
  64589. return _this;
  64590. }
  64591. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64592. /**
  64593. * Gets the current state of canRescale
  64594. */
  64595. get: function () {
  64596. return true;
  64597. },
  64598. enumerable: true,
  64599. configurable: true
  64600. });
  64601. DynamicTexture.prototype._recreate = function (textureSize) {
  64602. this._canvas.width = textureSize.width;
  64603. this._canvas.height = textureSize.height;
  64604. this.releaseInternalTexture();
  64605. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64606. };
  64607. /**
  64608. * Scales the texture
  64609. * @param ratio the scale factor to apply to both width and height
  64610. */
  64611. DynamicTexture.prototype.scale = function (ratio) {
  64612. var textureSize = this.getSize();
  64613. textureSize.width *= ratio;
  64614. textureSize.height *= ratio;
  64615. this._recreate(textureSize);
  64616. };
  64617. /**
  64618. * Resizes the texture
  64619. * @param width the new width
  64620. * @param height the new height
  64621. */
  64622. DynamicTexture.prototype.scaleTo = function (width, height) {
  64623. var textureSize = this.getSize();
  64624. textureSize.width = width;
  64625. textureSize.height = height;
  64626. this._recreate(textureSize);
  64627. };
  64628. /**
  64629. * Gets the context of the canvas used by the texture
  64630. * @returns the canvas context of the dynamic texture
  64631. */
  64632. DynamicTexture.prototype.getContext = function () {
  64633. return this._context;
  64634. };
  64635. /**
  64636. * Clears the texture
  64637. */
  64638. DynamicTexture.prototype.clear = function () {
  64639. var size = this.getSize();
  64640. this._context.fillRect(0, 0, size.width, size.height);
  64641. };
  64642. /**
  64643. * Updates the texture
  64644. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64645. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64646. */
  64647. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64648. if (premulAlpha === void 0) { premulAlpha = false; }
  64649. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64650. };
  64651. /**
  64652. * Draws text onto the texture
  64653. * @param text defines the text to be drawn
  64654. * @param x defines the placement of the text from the left
  64655. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64656. * @param font defines the font to be used with font-style, font-size, font-name
  64657. * @param color defines the color used for the text
  64658. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64659. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64660. * @param update defines whether texture is immediately update (default is true)
  64661. */
  64662. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64663. if (update === void 0) { update = true; }
  64664. var size = this.getSize();
  64665. if (clearColor) {
  64666. this._context.fillStyle = clearColor;
  64667. this._context.fillRect(0, 0, size.width, size.height);
  64668. }
  64669. this._context.font = font;
  64670. if (x === null || x === undefined) {
  64671. var textSize = this._context.measureText(text);
  64672. x = (size.width - textSize.width) / 2;
  64673. }
  64674. if (y === null || y === undefined) {
  64675. var fontSize = parseInt((font.replace(/\D/g, '')));
  64676. y = (size.height / 2) + (fontSize / 3.65);
  64677. }
  64678. this._context.fillStyle = color;
  64679. this._context.fillText(text, x, y);
  64680. if (update) {
  64681. this.update(invertY);
  64682. }
  64683. };
  64684. /**
  64685. * Clones the texture
  64686. * @returns the clone of the texture.
  64687. */
  64688. DynamicTexture.prototype.clone = function () {
  64689. var scene = this.getScene();
  64690. if (!scene) {
  64691. return this;
  64692. }
  64693. var textureSize = this.getSize();
  64694. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64695. // Base texture
  64696. newTexture.hasAlpha = this.hasAlpha;
  64697. newTexture.level = this.level;
  64698. // Dynamic Texture
  64699. newTexture.wrapU = this.wrapU;
  64700. newTexture.wrapV = this.wrapV;
  64701. return newTexture;
  64702. };
  64703. /** @hidden */
  64704. DynamicTexture.prototype._rebuild = function () {
  64705. this.update();
  64706. };
  64707. return DynamicTexture;
  64708. }(BABYLON.Texture));
  64709. BABYLON.DynamicTexture = DynamicTexture;
  64710. })(BABYLON || (BABYLON = {}));
  64711. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64712. var BABYLON;
  64713. (function (BABYLON) {
  64714. var VideoTexture = /** @class */ (function (_super) {
  64715. __extends(VideoTexture, _super);
  64716. /**
  64717. * Creates a video texture.
  64718. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64719. * @param {string | null} name optional name, will detect from video source, if not defined
  64720. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64721. * @param {BABYLON.Scene} scene is obviously the current scene.
  64722. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64723. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64724. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64725. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64726. */
  64727. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64728. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64729. if (invertY === void 0) { invertY = false; }
  64730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64731. if (settings === void 0) { settings = {
  64732. autoPlay: true,
  64733. loop: true,
  64734. autoUpdateTexture: true,
  64735. }; }
  64736. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64737. _this._onUserActionRequestedObservable = null;
  64738. _this._stillImageCaptured = false;
  64739. _this._poster = false;
  64740. _this._createInternalTexture = function () {
  64741. if (_this._texture != null) {
  64742. if (_this._poster) {
  64743. _this._texture.dispose();
  64744. _this._poster = false;
  64745. }
  64746. else {
  64747. return;
  64748. }
  64749. }
  64750. if (!_this._engine.needPOTTextures ||
  64751. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64752. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64753. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64754. }
  64755. else {
  64756. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64757. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64758. _this._generateMipMaps = false;
  64759. }
  64760. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64761. if (!_this.video.autoplay) {
  64762. var oldHandler_1 = _this.video.onplaying;
  64763. var error_1 = false;
  64764. _this.video.onplaying = function () {
  64765. _this.video.onplaying = oldHandler_1;
  64766. _this._texture.isReady = true;
  64767. _this._updateInternalTexture();
  64768. if (!error_1) {
  64769. _this.video.pause();
  64770. }
  64771. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64772. _this.onLoadObservable.notifyObservers(_this);
  64773. }
  64774. };
  64775. var playing = _this.video.play();
  64776. if (playing) {
  64777. playing.then(function () {
  64778. // Everything is good.
  64779. })
  64780. .catch(function () {
  64781. error_1 = true;
  64782. // On Chrome for instance, new policies might prevent playing without user interaction.
  64783. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64784. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64785. }
  64786. });
  64787. }
  64788. else {
  64789. _this.video.onplaying = oldHandler_1;
  64790. _this._texture.isReady = true;
  64791. _this._updateInternalTexture();
  64792. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64793. _this.onLoadObservable.notifyObservers(_this);
  64794. }
  64795. }
  64796. }
  64797. else {
  64798. _this._texture.isReady = true;
  64799. _this._updateInternalTexture();
  64800. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64801. _this.onLoadObservable.notifyObservers(_this);
  64802. }
  64803. }
  64804. };
  64805. _this.reset = function () {
  64806. if (_this._texture == null) {
  64807. return;
  64808. }
  64809. if (!_this._poster) {
  64810. _this._texture.dispose();
  64811. _this._texture = null;
  64812. }
  64813. };
  64814. _this._updateInternalTexture = function (e) {
  64815. if (_this._texture == null || !_this._texture.isReady) {
  64816. return;
  64817. }
  64818. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64819. return;
  64820. }
  64821. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64822. };
  64823. _this._engine = _this.getScene().getEngine();
  64824. _this._generateMipMaps = generateMipMaps;
  64825. _this._samplingMode = samplingMode;
  64826. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64827. _this.name = name || _this._getName(src);
  64828. _this.video = _this._getVideo(src);
  64829. if (settings.poster) {
  64830. _this.video.poster = settings.poster;
  64831. }
  64832. if (settings.autoPlay !== undefined) {
  64833. _this.video.autoplay = settings.autoPlay;
  64834. }
  64835. if (settings.loop !== undefined) {
  64836. _this.video.loop = settings.loop;
  64837. }
  64838. _this.video.setAttribute("playsinline", "");
  64839. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64840. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64841. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64842. _this.video.addEventListener("emptied", _this.reset);
  64843. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64844. _this._createInternalTexture();
  64845. }
  64846. if (settings.poster) {
  64847. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  64848. _this._poster = true;
  64849. }
  64850. return _this;
  64851. }
  64852. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64853. get: function () {
  64854. if (!this._onUserActionRequestedObservable) {
  64855. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64856. }
  64857. return this._onUserActionRequestedObservable;
  64858. },
  64859. enumerable: true,
  64860. configurable: true
  64861. });
  64862. VideoTexture.prototype._getName = function (src) {
  64863. if (src instanceof HTMLVideoElement) {
  64864. return src.currentSrc;
  64865. }
  64866. if (typeof src === "object") {
  64867. return src.toString();
  64868. }
  64869. return src;
  64870. };
  64871. ;
  64872. VideoTexture.prototype._getVideo = function (src) {
  64873. if (src instanceof HTMLVideoElement) {
  64874. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64875. return src;
  64876. }
  64877. var video = document.createElement("video");
  64878. if (typeof src === "string") {
  64879. BABYLON.Tools.SetCorsBehavior(src, video);
  64880. video.src = src;
  64881. }
  64882. else {
  64883. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64884. src.forEach(function (url) {
  64885. var source = document.createElement("source");
  64886. source.src = url;
  64887. video.appendChild(source);
  64888. });
  64889. }
  64890. return video;
  64891. };
  64892. ;
  64893. /**
  64894. * Internal method to initiate `update`.
  64895. */
  64896. VideoTexture.prototype._rebuild = function () {
  64897. this.update();
  64898. };
  64899. /**
  64900. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64901. */
  64902. VideoTexture.prototype.update = function () {
  64903. if (!this.autoUpdateTexture) {
  64904. // Expecting user to call `updateTexture` manually
  64905. return;
  64906. }
  64907. this.updateTexture(true);
  64908. };
  64909. /**
  64910. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64911. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64912. */
  64913. VideoTexture.prototype.updateTexture = function (isVisible) {
  64914. if (!isVisible) {
  64915. return;
  64916. }
  64917. if (this.video.paused && this._stillImageCaptured) {
  64918. return;
  64919. }
  64920. this._stillImageCaptured = true;
  64921. this._updateInternalTexture();
  64922. };
  64923. /**
  64924. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64925. * @param url New url.
  64926. */
  64927. VideoTexture.prototype.updateURL = function (url) {
  64928. this.video.src = url;
  64929. };
  64930. VideoTexture.prototype.dispose = function () {
  64931. _super.prototype.dispose.call(this);
  64932. if (this._onUserActionRequestedObservable) {
  64933. this._onUserActionRequestedObservable.clear();
  64934. this._onUserActionRequestedObservable = null;
  64935. }
  64936. this.video.removeEventListener("canplay", this._createInternalTexture);
  64937. this.video.removeEventListener("paused", this._updateInternalTexture);
  64938. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64939. this.video.removeEventListener("emptied", this.reset);
  64940. this.video.pause();
  64941. };
  64942. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64943. var video = document.createElement("video");
  64944. video.setAttribute('autoplay', '');
  64945. video.setAttribute('muted', '');
  64946. video.setAttribute('playsinline', '');
  64947. var constraintsDeviceId;
  64948. if (constraints && constraints.deviceId) {
  64949. constraintsDeviceId = {
  64950. exact: constraints.deviceId,
  64951. };
  64952. }
  64953. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64954. if (navigator.mediaDevices) {
  64955. navigator.mediaDevices.getUserMedia({ video: constraints })
  64956. .then(function (stream) {
  64957. if (video.mozSrcObject !== undefined) {
  64958. // hack for Firefox < 19
  64959. video.mozSrcObject = stream;
  64960. }
  64961. else {
  64962. video.srcObject = stream;
  64963. }
  64964. var onPlaying = function () {
  64965. if (onReady) {
  64966. onReady(new VideoTexture("video", video, scene, true, true));
  64967. }
  64968. video.removeEventListener("playing", onPlaying);
  64969. };
  64970. video.addEventListener("playing", onPlaying);
  64971. video.play();
  64972. })
  64973. .catch(function (err) {
  64974. BABYLON.Tools.Error(err.name);
  64975. });
  64976. }
  64977. else {
  64978. navigator.getUserMedia =
  64979. navigator.getUserMedia ||
  64980. navigator.webkitGetUserMedia ||
  64981. navigator.mozGetUserMedia ||
  64982. navigator.msGetUserMedia;
  64983. if (navigator.getUserMedia) {
  64984. navigator.getUserMedia({
  64985. video: {
  64986. deviceId: constraintsDeviceId,
  64987. width: {
  64988. min: (constraints && constraints.minWidth) || 256,
  64989. max: (constraints && constraints.maxWidth) || 640,
  64990. },
  64991. height: {
  64992. min: (constraints && constraints.minHeight) || 256,
  64993. max: (constraints && constraints.maxHeight) || 480,
  64994. },
  64995. },
  64996. }, function (stream) {
  64997. if (video.mozSrcObject !== undefined) {
  64998. // hack for Firefox < 19
  64999. video.mozSrcObject = stream;
  65000. }
  65001. else {
  65002. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65003. }
  65004. video.play();
  65005. if (onReady) {
  65006. onReady(new VideoTexture("video", video, scene, true, true));
  65007. }
  65008. }, function (e) {
  65009. BABYLON.Tools.Error(e.name);
  65010. });
  65011. }
  65012. }
  65013. };
  65014. return VideoTexture;
  65015. }(BABYLON.Texture));
  65016. BABYLON.VideoTexture = VideoTexture;
  65017. })(BABYLON || (BABYLON = {}));
  65018. //# sourceMappingURL=babylon.videoTexture.js.map
  65019. var BABYLON;
  65020. (function (BABYLON) {
  65021. var RawTexture = /** @class */ (function (_super) {
  65022. __extends(RawTexture, _super);
  65023. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65024. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65025. if (invertY === void 0) { invertY = false; }
  65026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65027. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65028. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65029. _this.format = format;
  65030. _this._engine = scene.getEngine();
  65031. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65032. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65033. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65034. return _this;
  65035. }
  65036. RawTexture.prototype.update = function (data) {
  65037. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65038. };
  65039. // Statics
  65040. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65041. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65042. if (invertY === void 0) { invertY = false; }
  65043. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65044. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65045. };
  65046. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65047. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65048. if (invertY === void 0) { invertY = false; }
  65049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65050. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65051. };
  65052. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65053. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65054. if (invertY === void 0) { invertY = false; }
  65055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65056. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65057. };
  65058. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65059. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65060. if (invertY === void 0) { invertY = false; }
  65061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65062. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65063. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65064. };
  65065. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65066. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65067. if (invertY === void 0) { invertY = false; }
  65068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65069. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65070. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65071. };
  65072. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65073. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65074. if (invertY === void 0) { invertY = false; }
  65075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65076. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65077. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65078. };
  65079. return RawTexture;
  65080. }(BABYLON.Texture));
  65081. BABYLON.RawTexture = RawTexture;
  65082. })(BABYLON || (BABYLON = {}));
  65083. //# sourceMappingURL=babylon.rawTexture.js.map
  65084. var BABYLON;
  65085. (function (BABYLON) {
  65086. /**
  65087. * Class used to store 3D textures containing user data
  65088. */
  65089. var RawTexture3D = /** @class */ (function (_super) {
  65090. __extends(RawTexture3D, _super);
  65091. /**
  65092. * Create a new RawTexture3D
  65093. * @param data defines the data of the texture
  65094. * @param width defines the width of the texture
  65095. * @param height defines the height of the texture
  65096. * @param depth defines the depth of the texture
  65097. * @param format defines the texture format to use
  65098. * @param scene defines the hosting scene
  65099. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65100. * @param invertY defines if texture must be stored with Y axis inverted
  65101. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65102. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65103. */
  65104. function RawTexture3D(data, width, height, depth,
  65105. /** Gets or sets the texture format to use */
  65106. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65107. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65108. if (invertY === void 0) { invertY = false; }
  65109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65110. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65111. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65112. _this.format = format;
  65113. _this._engine = scene.getEngine();
  65114. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65115. _this.is3D = true;
  65116. return _this;
  65117. }
  65118. /**
  65119. * Update the texture with new data
  65120. * @param data defines the data to store in the texture
  65121. */
  65122. RawTexture3D.prototype.update = function (data) {
  65123. if (!this._texture) {
  65124. return;
  65125. }
  65126. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65127. };
  65128. return RawTexture3D;
  65129. }(BABYLON.Texture));
  65130. BABYLON.RawTexture3D = RawTexture3D;
  65131. })(BABYLON || (BABYLON = {}));
  65132. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65133. var BABYLON;
  65134. (function (BABYLON) {
  65135. /**
  65136. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65137. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65138. */
  65139. var PostProcessManager = /** @class */ (function () {
  65140. /**
  65141. * Creates a new instance PostProcess
  65142. * @param scene The scene that the post process is associated with.
  65143. */
  65144. function PostProcessManager(scene) {
  65145. this._vertexBuffers = {};
  65146. this._scene = scene;
  65147. }
  65148. PostProcessManager.prototype._prepareBuffers = function () {
  65149. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65150. return;
  65151. }
  65152. // VBO
  65153. var vertices = [];
  65154. vertices.push(1, 1);
  65155. vertices.push(-1, 1);
  65156. vertices.push(-1, -1);
  65157. vertices.push(1, -1);
  65158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65159. this._buildIndexBuffer();
  65160. };
  65161. PostProcessManager.prototype._buildIndexBuffer = function () {
  65162. // Indices
  65163. var indices = [];
  65164. indices.push(0);
  65165. indices.push(1);
  65166. indices.push(2);
  65167. indices.push(0);
  65168. indices.push(2);
  65169. indices.push(3);
  65170. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65171. };
  65172. /**
  65173. * Rebuilds the vertex buffers of the manager.
  65174. */
  65175. PostProcessManager.prototype._rebuild = function () {
  65176. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65177. if (!vb) {
  65178. return;
  65179. }
  65180. vb._rebuild();
  65181. this._buildIndexBuffer();
  65182. };
  65183. // Methods
  65184. /**
  65185. * Prepares a frame to be run through a post process.
  65186. * @param sourceTexture The input texture to the post procesess. (default: null)
  65187. * @param postProcesses An array of post processes to be run. (default: null)
  65188. * @returns True if the post processes were able to be run.
  65189. */
  65190. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65191. if (sourceTexture === void 0) { sourceTexture = null; }
  65192. if (postProcesses === void 0) { postProcesses = null; }
  65193. var camera = this._scene.activeCamera;
  65194. if (!camera) {
  65195. return false;
  65196. }
  65197. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65198. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65199. return false;
  65200. }
  65201. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65202. return true;
  65203. };
  65204. /**
  65205. * Manually render a set of post processes to a texture.
  65206. * @param postProcesses An array of post processes to be run.
  65207. * @param targetTexture The target texture to render to.
  65208. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65209. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65210. * @param lodLevel defines which lod of the texture to render to
  65211. */
  65212. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65213. if (targetTexture === void 0) { targetTexture = null; }
  65214. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65215. if (faceIndex === void 0) { faceIndex = 0; }
  65216. if (lodLevel === void 0) { lodLevel = 0; }
  65217. var engine = this._scene.getEngine();
  65218. for (var index = 0; index < postProcesses.length; index++) {
  65219. if (index < postProcesses.length - 1) {
  65220. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65221. }
  65222. else {
  65223. if (targetTexture) {
  65224. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65225. }
  65226. else {
  65227. engine.restoreDefaultFramebuffer();
  65228. }
  65229. }
  65230. var pp = postProcesses[index];
  65231. var effect = pp.apply();
  65232. if (effect) {
  65233. pp.onBeforeRenderObservable.notifyObservers(effect);
  65234. // VBOs
  65235. this._prepareBuffers();
  65236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65237. // Draw order
  65238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65239. pp.onAfterRenderObservable.notifyObservers(effect);
  65240. }
  65241. }
  65242. // Restore depth buffer
  65243. engine.setDepthBuffer(true);
  65244. engine.setDepthWrite(true);
  65245. };
  65246. /**
  65247. * Finalize the result of the output of the postprocesses.
  65248. * @param doNotPresent If true the result will not be displayed to the screen.
  65249. * @param targetTexture The target texture to render to.
  65250. * @param faceIndex The index of the face to bind the target texture to.
  65251. * @param postProcesses The array of post processes to render.
  65252. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65253. */
  65254. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65255. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65256. var camera = this._scene.activeCamera;
  65257. if (!camera) {
  65258. return;
  65259. }
  65260. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65261. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65262. return;
  65263. }
  65264. var engine = this._scene.getEngine();
  65265. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65266. var pp = postProcesses[index];
  65267. if (index < len - 1) {
  65268. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65269. }
  65270. else {
  65271. if (targetTexture) {
  65272. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65273. pp._outputTexture = targetTexture;
  65274. }
  65275. else {
  65276. engine.restoreDefaultFramebuffer();
  65277. pp._outputTexture = null;
  65278. }
  65279. }
  65280. if (doNotPresent) {
  65281. break;
  65282. }
  65283. var effect = pp.apply();
  65284. if (effect) {
  65285. pp.onBeforeRenderObservable.notifyObservers(effect);
  65286. // VBOs
  65287. this._prepareBuffers();
  65288. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65289. // Draw order
  65290. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65291. pp.onAfterRenderObservable.notifyObservers(effect);
  65292. }
  65293. }
  65294. // Restore states
  65295. engine.setDepthBuffer(true);
  65296. engine.setDepthWrite(true);
  65297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65298. };
  65299. /**
  65300. * Disposes of the post process manager.
  65301. */
  65302. PostProcessManager.prototype.dispose = function () {
  65303. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65304. if (buffer) {
  65305. buffer.dispose();
  65306. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65307. }
  65308. if (this._indexBuffer) {
  65309. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65310. this._indexBuffer = null;
  65311. }
  65312. };
  65313. return PostProcessManager;
  65314. }());
  65315. BABYLON.PostProcessManager = PostProcessManager;
  65316. })(BABYLON || (BABYLON = {}));
  65317. //# sourceMappingURL=babylon.postProcessManager.js.map
  65318. var BABYLON;
  65319. (function (BABYLON) {
  65320. /**
  65321. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65322. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65323. */
  65324. var PostProcess = /** @class */ (function () {
  65325. /**
  65326. * Creates a new instance PostProcess
  65327. * @param name The name of the PostProcess.
  65328. * @param fragmentUrl The url of the fragment shader to be used.
  65329. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65330. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65331. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65332. * @param camera The camera to apply the render pass to.
  65333. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65334. * @param engine The engine which the post process will be applied. (default: current engine)
  65335. * @param reusable If the post process can be reused on the same frame. (default: false)
  65336. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65337. * @param textureType Type of textures used when performing the post process. (default: 0)
  65338. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65339. * @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
  65340. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65341. */
  65342. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65344. if (defines === void 0) { defines = null; }
  65345. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65346. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65347. if (blockCompilation === void 0) { blockCompilation = false; }
  65348. this.name = name;
  65349. /**
  65350. * Width of the texture to apply the post process on
  65351. */
  65352. this.width = -1;
  65353. /**
  65354. * Height of the texture to apply the post process on
  65355. */
  65356. this.height = -1;
  65357. /**
  65358. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65359. */
  65360. this._outputTexture = null;
  65361. /**
  65362. * If the buffer needs to be cleared before applying the post process. (default: true)
  65363. * Should be set to false if shader will overwrite all previous pixels.
  65364. */
  65365. this.autoClear = true;
  65366. /**
  65367. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65368. */
  65369. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65370. /**
  65371. * Animations to be used for the post processing
  65372. */
  65373. this.animations = new Array();
  65374. /**
  65375. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65376. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65377. */
  65378. this.enablePixelPerfectMode = false;
  65379. /**
  65380. * Force the postprocess to be applied without taking in account viewport
  65381. */
  65382. this.forceFullscreenViewport = true;
  65383. /**
  65384. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65385. *
  65386. * | Value | Type | Description |
  65387. * | ----- | ----------------------------------- | ----------- |
  65388. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65389. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65390. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65391. *
  65392. */
  65393. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65394. /**
  65395. * Force textures to be a power of two (default: false)
  65396. */
  65397. this.alwaysForcePOT = false;
  65398. /**
  65399. * Number of sample textures (default: 1)
  65400. */
  65401. this.samples = 1;
  65402. /**
  65403. * Modify the scale of the post process to be the same as the viewport (default: false)
  65404. */
  65405. this.adaptScaleToCurrentViewport = false;
  65406. this._reusable = false;
  65407. /**
  65408. * Smart array of input and output textures for the post process.
  65409. */
  65410. this._textures = new BABYLON.SmartArray(2);
  65411. /**
  65412. * The index in _textures that corresponds to the output texture.
  65413. */
  65414. this._currentRenderTextureInd = 0;
  65415. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65416. this._texelSize = BABYLON.Vector2.Zero();
  65417. // Events
  65418. /**
  65419. * An event triggered when the postprocess is activated.
  65420. */
  65421. this.onActivateObservable = new BABYLON.Observable();
  65422. /**
  65423. * An event triggered when the postprocess changes its size.
  65424. */
  65425. this.onSizeChangedObservable = new BABYLON.Observable();
  65426. /**
  65427. * An event triggered when the postprocess applies its effect.
  65428. */
  65429. this.onApplyObservable = new BABYLON.Observable();
  65430. /**
  65431. * An event triggered before rendering the postprocess
  65432. */
  65433. this.onBeforeRenderObservable = new BABYLON.Observable();
  65434. /**
  65435. * An event triggered after rendering the postprocess
  65436. */
  65437. this.onAfterRenderObservable = new BABYLON.Observable();
  65438. if (camera != null) {
  65439. this._camera = camera;
  65440. this._scene = camera.getScene();
  65441. camera.attachPostProcess(this);
  65442. this._engine = this._scene.getEngine();
  65443. this._scene.postProcesses.push(this);
  65444. }
  65445. else if (engine) {
  65446. this._engine = engine;
  65447. this._engine.postProcesses.push(this);
  65448. }
  65449. this._options = options;
  65450. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65451. this._reusable = reusable || false;
  65452. this._textureType = textureType;
  65453. this._samplers = samplers || [];
  65454. this._samplers.push("textureSampler");
  65455. this._fragmentUrl = fragmentUrl;
  65456. this._vertexUrl = vertexUrl;
  65457. this._parameters = parameters || [];
  65458. this._parameters.push("scale");
  65459. this._indexParameters = indexParameters;
  65460. if (!blockCompilation) {
  65461. this.updateEffect(defines);
  65462. }
  65463. }
  65464. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65465. /**
  65466. * A function that is added to the onActivateObservable
  65467. */
  65468. set: function (callback) {
  65469. if (this._onActivateObserver) {
  65470. this.onActivateObservable.remove(this._onActivateObserver);
  65471. }
  65472. if (callback) {
  65473. this._onActivateObserver = this.onActivateObservable.add(callback);
  65474. }
  65475. },
  65476. enumerable: true,
  65477. configurable: true
  65478. });
  65479. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65480. /**
  65481. * A function that is added to the onSizeChangedObservable
  65482. */
  65483. set: function (callback) {
  65484. if (this._onSizeChangedObserver) {
  65485. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65486. }
  65487. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65488. },
  65489. enumerable: true,
  65490. configurable: true
  65491. });
  65492. Object.defineProperty(PostProcess.prototype, "onApply", {
  65493. /**
  65494. * A function that is added to the onApplyObservable
  65495. */
  65496. set: function (callback) {
  65497. if (this._onApplyObserver) {
  65498. this.onApplyObservable.remove(this._onApplyObserver);
  65499. }
  65500. this._onApplyObserver = this.onApplyObservable.add(callback);
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65506. /**
  65507. * A function that is added to the onBeforeRenderObservable
  65508. */
  65509. set: function (callback) {
  65510. if (this._onBeforeRenderObserver) {
  65511. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65512. }
  65513. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65514. },
  65515. enumerable: true,
  65516. configurable: true
  65517. });
  65518. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65519. /**
  65520. * A function that is added to the onAfterRenderObservable
  65521. */
  65522. set: function (callback) {
  65523. if (this._onAfterRenderObserver) {
  65524. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65525. }
  65526. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65527. },
  65528. enumerable: true,
  65529. configurable: true
  65530. });
  65531. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65532. /**
  65533. * 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
  65534. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65535. */
  65536. get: function () {
  65537. return this._textures.data[this._currentRenderTextureInd];
  65538. },
  65539. set: function (value) {
  65540. this._forcedOutputTexture = value;
  65541. },
  65542. enumerable: true,
  65543. configurable: true
  65544. });
  65545. /**
  65546. * Gets the camera which post process is applied to.
  65547. * @returns The camera the post process is applied to.
  65548. */
  65549. PostProcess.prototype.getCamera = function () {
  65550. return this._camera;
  65551. };
  65552. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65553. /**
  65554. * Gets the texel size of the postprocess.
  65555. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65556. */
  65557. get: function () {
  65558. if (this._shareOutputWithPostProcess) {
  65559. return this._shareOutputWithPostProcess.texelSize;
  65560. }
  65561. if (this._forcedOutputTexture) {
  65562. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65563. }
  65564. return this._texelSize;
  65565. },
  65566. enumerable: true,
  65567. configurable: true
  65568. });
  65569. /**
  65570. * Gets the engine which this post process belongs to.
  65571. * @returns The engine the post process was enabled with.
  65572. */
  65573. PostProcess.prototype.getEngine = function () {
  65574. return this._engine;
  65575. };
  65576. /**
  65577. * The effect that is created when initializing the post process.
  65578. * @returns The created effect corrisponding the the postprocess.
  65579. */
  65580. PostProcess.prototype.getEffect = function () {
  65581. return this._effect;
  65582. };
  65583. /**
  65584. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65585. * @param postProcess The post process to share the output with.
  65586. * @returns This post process.
  65587. */
  65588. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65589. this._disposeTextures();
  65590. this._shareOutputWithPostProcess = postProcess;
  65591. return this;
  65592. };
  65593. /**
  65594. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65595. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65596. */
  65597. PostProcess.prototype.useOwnOutput = function () {
  65598. if (this._textures.length == 0) {
  65599. this._textures = new BABYLON.SmartArray(2);
  65600. }
  65601. this._shareOutputWithPostProcess = null;
  65602. };
  65603. /**
  65604. * Updates the effect with the current post process compile time values and recompiles the shader.
  65605. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65606. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65607. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65608. * @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
  65609. * @param onCompiled Called when the shader has been compiled.
  65610. * @param onError Called if there is an error when compiling a shader.
  65611. */
  65612. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65613. if (defines === void 0) { defines = null; }
  65614. if (uniforms === void 0) { uniforms = null; }
  65615. if (samplers === void 0) { samplers = null; }
  65616. 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);
  65617. };
  65618. /**
  65619. * The post process is reusable if it can be used multiple times within one frame.
  65620. * @returns If the post process is reusable
  65621. */
  65622. PostProcess.prototype.isReusable = function () {
  65623. return this._reusable;
  65624. };
  65625. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65626. PostProcess.prototype.markTextureDirty = function () {
  65627. this.width = -1;
  65628. };
  65629. /**
  65630. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65631. * 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.
  65632. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65633. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65634. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65635. * @returns The target texture that was bound to be written to.
  65636. */
  65637. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65638. var _this = this;
  65639. if (sourceTexture === void 0) { sourceTexture = null; }
  65640. camera = camera || this._camera;
  65641. var scene = camera.getScene();
  65642. var engine = scene.getEngine();
  65643. var maxSize = engine.getCaps().maxTextureSize;
  65644. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65645. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65646. // 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
  65647. var webVRCamera = camera.parent;
  65648. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65649. requiredWidth /= 2;
  65650. }
  65651. var desiredWidth = (this._options.width || requiredWidth);
  65652. var desiredHeight = this._options.height || requiredHeight;
  65653. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65654. if (this.adaptScaleToCurrentViewport) {
  65655. var currentViewport = engine.currentViewport;
  65656. if (currentViewport) {
  65657. desiredWidth *= currentViewport.width;
  65658. desiredHeight *= currentViewport.height;
  65659. }
  65660. }
  65661. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65662. if (!this._options.width) {
  65663. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65664. }
  65665. if (!this._options.height) {
  65666. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65667. }
  65668. }
  65669. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65670. if (this._textures.length > 0) {
  65671. for (var i = 0; i < this._textures.length; i++) {
  65672. this._engine._releaseTexture(this._textures.data[i]);
  65673. }
  65674. this._textures.reset();
  65675. }
  65676. this.width = desiredWidth;
  65677. this.height = desiredHeight;
  65678. var textureSize = { width: this.width, height: this.height };
  65679. var textureOptions = {
  65680. generateMipMaps: false,
  65681. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65682. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65683. samplingMode: this.renderTargetSamplingMode,
  65684. type: this._textureType
  65685. };
  65686. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65687. if (this._reusable) {
  65688. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65689. }
  65690. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65691. this.onSizeChangedObservable.notifyObservers(this);
  65692. }
  65693. this._textures.forEach(function (texture) {
  65694. if (texture.samples !== _this.samples) {
  65695. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65696. }
  65697. });
  65698. }
  65699. var target;
  65700. if (this._shareOutputWithPostProcess) {
  65701. target = this._shareOutputWithPostProcess.inputTexture;
  65702. }
  65703. else if (this._forcedOutputTexture) {
  65704. target = this._forcedOutputTexture;
  65705. this.width = this._forcedOutputTexture.width;
  65706. this.height = this._forcedOutputTexture.height;
  65707. }
  65708. else {
  65709. target = this.inputTexture;
  65710. }
  65711. // Bind the input of this post process to be used as the output of the previous post process.
  65712. if (this.enablePixelPerfectMode) {
  65713. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65714. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65715. }
  65716. else {
  65717. this._scaleRatio.copyFromFloats(1, 1);
  65718. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65719. }
  65720. this.onActivateObservable.notifyObservers(camera);
  65721. // Clear
  65722. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65723. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65724. }
  65725. if (this._reusable) {
  65726. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65727. }
  65728. return target;
  65729. };
  65730. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65731. /**
  65732. * If the post process is supported.
  65733. */
  65734. get: function () {
  65735. return this._effect.isSupported;
  65736. },
  65737. enumerable: true,
  65738. configurable: true
  65739. });
  65740. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65741. /**
  65742. * The aspect ratio of the output texture.
  65743. */
  65744. get: function () {
  65745. if (this._shareOutputWithPostProcess) {
  65746. return this._shareOutputWithPostProcess.aspectRatio;
  65747. }
  65748. if (this._forcedOutputTexture) {
  65749. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65750. }
  65751. return this.width / this.height;
  65752. },
  65753. enumerable: true,
  65754. configurable: true
  65755. });
  65756. /**
  65757. * Get a value indicating if the post-process is ready to be used
  65758. * @returns true if the post-process is ready (shader is compiled)
  65759. */
  65760. PostProcess.prototype.isReady = function () {
  65761. return this._effect && this._effect.isReady();
  65762. };
  65763. /**
  65764. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65765. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65766. */
  65767. PostProcess.prototype.apply = function () {
  65768. // Check
  65769. if (!this._effect || !this._effect.isReady())
  65770. return null;
  65771. // States
  65772. this._engine.enableEffect(this._effect);
  65773. this._engine.setState(false);
  65774. this._engine.setDepthBuffer(false);
  65775. this._engine.setDepthWrite(false);
  65776. // Alpha
  65777. this._engine.setAlphaMode(this.alphaMode);
  65778. if (this.alphaConstants) {
  65779. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65780. }
  65781. // Bind the output texture of the preivous post process as the input to this post process.
  65782. var source;
  65783. if (this._shareOutputWithPostProcess) {
  65784. source = this._shareOutputWithPostProcess.inputTexture;
  65785. }
  65786. else if (this._forcedOutputTexture) {
  65787. source = this._forcedOutputTexture;
  65788. }
  65789. else {
  65790. source = this.inputTexture;
  65791. }
  65792. this._effect._bindTexture("textureSampler", source);
  65793. // Parameters
  65794. this._effect.setVector2("scale", this._scaleRatio);
  65795. this.onApplyObservable.notifyObservers(this._effect);
  65796. return this._effect;
  65797. };
  65798. PostProcess.prototype._disposeTextures = function () {
  65799. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65800. return;
  65801. }
  65802. if (this._textures.length > 0) {
  65803. for (var i = 0; i < this._textures.length; i++) {
  65804. this._engine._releaseTexture(this._textures.data[i]);
  65805. }
  65806. }
  65807. this._textures.dispose();
  65808. };
  65809. /**
  65810. * Disposes the post process.
  65811. * @param camera The camera to dispose the post process on.
  65812. */
  65813. PostProcess.prototype.dispose = function (camera) {
  65814. camera = camera || this._camera;
  65815. this._disposeTextures();
  65816. if (this._scene) {
  65817. var index_1 = this._scene.postProcesses.indexOf(this);
  65818. if (index_1 !== -1) {
  65819. this._scene.postProcesses.splice(index_1, 1);
  65820. }
  65821. }
  65822. else {
  65823. var index_2 = this._engine.postProcesses.indexOf(this);
  65824. if (index_2 !== -1) {
  65825. this._engine.postProcesses.splice(index_2, 1);
  65826. }
  65827. }
  65828. if (!camera) {
  65829. return;
  65830. }
  65831. camera.detachPostProcess(this);
  65832. var index = camera._postProcesses.indexOf(this);
  65833. if (index === 0 && camera._postProcesses.length > 0) {
  65834. var firstPostProcess = this._camera._getFirstPostProcess();
  65835. if (firstPostProcess) {
  65836. firstPostProcess.markTextureDirty();
  65837. }
  65838. }
  65839. this.onActivateObservable.clear();
  65840. this.onAfterRenderObservable.clear();
  65841. this.onApplyObservable.clear();
  65842. this.onBeforeRenderObservable.clear();
  65843. this.onSizeChangedObservable.clear();
  65844. };
  65845. return PostProcess;
  65846. }());
  65847. BABYLON.PostProcess = PostProcess;
  65848. })(BABYLON || (BABYLON = {}));
  65849. //# sourceMappingURL=babylon.postProcess.js.map
  65850. var BABYLON;
  65851. (function (BABYLON) {
  65852. var PassPostProcess = /** @class */ (function (_super) {
  65853. __extends(PassPostProcess, _super);
  65854. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65855. if (camera === void 0) { camera = null; }
  65856. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65857. if (blockCompilation === void 0) { blockCompilation = false; }
  65858. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65859. }
  65860. return PassPostProcess;
  65861. }(BABYLON.PostProcess));
  65862. BABYLON.PassPostProcess = PassPostProcess;
  65863. })(BABYLON || (BABYLON = {}));
  65864. //# sourceMappingURL=babylon.passPostProcess.js.map
  65865. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65866. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65867. s = arguments[i];
  65868. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65869. t[p] = s[p];
  65870. }
  65871. return t;
  65872. };
  65873. var BABYLON;
  65874. (function (BABYLON) {
  65875. /**
  65876. * Default implementation IShadowGenerator.
  65877. * This is the main object responsible of generating shadows in the framework.
  65878. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65879. */
  65880. var ShadowGenerator = /** @class */ (function () {
  65881. /**
  65882. * Creates a ShadowGenerator object.
  65883. * A ShadowGenerator is the required tool to use the shadows.
  65884. * Each light casting shadows needs to use its own ShadowGenerator.
  65885. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65886. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65887. * @param light The light object generating the shadows.
  65888. * @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.
  65889. */
  65890. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65891. this._bias = 0.00005;
  65892. this._normalBias = 0;
  65893. this._blurBoxOffset = 1;
  65894. this._blurScale = 2;
  65895. this._blurKernel = 1;
  65896. this._useKernelBlur = false;
  65897. this._filter = ShadowGenerator.FILTER_NONE;
  65898. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65899. this._contactHardeningLightSizeUVRatio = 0.1;
  65900. this._darkness = 0;
  65901. this._transparencyShadow = false;
  65902. /**
  65903. * Controls the extent to which the shadows fade out at the edge of the frustum
  65904. * Used only by directionals and spots
  65905. */
  65906. this.frustumEdgeFalloff = 0;
  65907. /**
  65908. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65909. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65910. * It might on the other hand introduce peter panning.
  65911. */
  65912. this.forceBackFacesOnly = false;
  65913. this._lightDirection = BABYLON.Vector3.Zero();
  65914. this._viewMatrix = BABYLON.Matrix.Zero();
  65915. this._projectionMatrix = BABYLON.Matrix.Zero();
  65916. this._transformMatrix = BABYLON.Matrix.Zero();
  65917. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65918. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65919. this._currentFaceIndex = 0;
  65920. this._currentFaceIndexCache = 0;
  65921. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65922. this._mapSize = mapSize;
  65923. this._light = light;
  65924. this._scene = light.getScene();
  65925. light._shadowGenerator = this;
  65926. // Texture type fallback from float to int if not supported.
  65927. var caps = this._scene.getEngine().getCaps();
  65928. if (!useFullFloatFirst) {
  65929. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65930. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65931. }
  65932. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65933. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65934. }
  65935. else {
  65936. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65937. }
  65938. }
  65939. else {
  65940. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65941. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65942. }
  65943. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65944. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65945. }
  65946. else {
  65947. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65948. }
  65949. }
  65950. this._initializeGenerator();
  65951. this._applyFilterValues();
  65952. }
  65953. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65954. /**
  65955. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65956. */
  65957. get: function () {
  65958. return this._bias;
  65959. },
  65960. /**
  65961. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65962. */
  65963. set: function (bias) {
  65964. this._bias = bias;
  65965. },
  65966. enumerable: true,
  65967. configurable: true
  65968. });
  65969. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65970. /**
  65971. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65972. */
  65973. get: function () {
  65974. return this._normalBias;
  65975. },
  65976. /**
  65977. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65978. */
  65979. set: function (normalBias) {
  65980. this._normalBias = normalBias;
  65981. },
  65982. enumerable: true,
  65983. configurable: true
  65984. });
  65985. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65986. /**
  65987. * Gets the blur box offset: offset applied during the blur pass.
  65988. * Only usefull if useKernelBlur = false
  65989. */
  65990. get: function () {
  65991. return this._blurBoxOffset;
  65992. },
  65993. /**
  65994. * Sets the blur box offset: offset applied during the blur pass.
  65995. * Only usefull if useKernelBlur = false
  65996. */
  65997. set: function (value) {
  65998. if (this._blurBoxOffset === value) {
  65999. return;
  66000. }
  66001. this._blurBoxOffset = value;
  66002. this._disposeBlurPostProcesses();
  66003. },
  66004. enumerable: true,
  66005. configurable: true
  66006. });
  66007. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66008. /**
  66009. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66010. * 2 means half of the size.
  66011. */
  66012. get: function () {
  66013. return this._blurScale;
  66014. },
  66015. /**
  66016. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66017. * 2 means half of the size.
  66018. */
  66019. set: function (value) {
  66020. if (this._blurScale === value) {
  66021. return;
  66022. }
  66023. this._blurScale = value;
  66024. this._disposeBlurPostProcesses();
  66025. },
  66026. enumerable: true,
  66027. configurable: true
  66028. });
  66029. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66030. /**
  66031. * Gets the blur kernel: kernel size of the blur pass.
  66032. * Only usefull if useKernelBlur = true
  66033. */
  66034. get: function () {
  66035. return this._blurKernel;
  66036. },
  66037. /**
  66038. * Sets the blur kernel: kernel size of the blur pass.
  66039. * Only usefull if useKernelBlur = true
  66040. */
  66041. set: function (value) {
  66042. if (this._blurKernel === value) {
  66043. return;
  66044. }
  66045. this._blurKernel = value;
  66046. this._disposeBlurPostProcesses();
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66052. /**
  66053. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66054. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66055. */
  66056. get: function () {
  66057. return this._useKernelBlur;
  66058. },
  66059. /**
  66060. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66061. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66062. */
  66063. set: function (value) {
  66064. if (this._useKernelBlur === value) {
  66065. return;
  66066. }
  66067. this._useKernelBlur = value;
  66068. this._disposeBlurPostProcesses();
  66069. },
  66070. enumerable: true,
  66071. configurable: true
  66072. });
  66073. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66074. /**
  66075. * Gets the depth scale used in ESM mode.
  66076. */
  66077. get: function () {
  66078. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66079. },
  66080. /**
  66081. * Sets the depth scale used in ESM mode.
  66082. * This can override the scale stored on the light.
  66083. */
  66084. set: function (value) {
  66085. this._depthScale = value;
  66086. },
  66087. enumerable: true,
  66088. configurable: true
  66089. });
  66090. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66091. /**
  66092. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66093. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66094. */
  66095. get: function () {
  66096. return this._filter;
  66097. },
  66098. /**
  66099. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66100. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66101. */
  66102. set: function (value) {
  66103. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66104. if (this._light.needCube()) {
  66105. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66106. this.useExponentialShadowMap = true;
  66107. return;
  66108. }
  66109. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66110. this.useCloseExponentialShadowMap = true;
  66111. return;
  66112. }
  66113. // PCF on cubemap would also be expensive
  66114. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66115. this.usePoissonSampling = true;
  66116. return;
  66117. }
  66118. }
  66119. // Weblg1 fallback for PCF.
  66120. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66121. if (this._scene.getEngine().webGLVersion === 1) {
  66122. this.usePoissonSampling = true;
  66123. return;
  66124. }
  66125. }
  66126. if (this._filter === value) {
  66127. return;
  66128. }
  66129. this._filter = value;
  66130. this._disposeBlurPostProcesses();
  66131. this._applyFilterValues();
  66132. this._light._markMeshesAsLightDirty();
  66133. },
  66134. enumerable: true,
  66135. configurable: true
  66136. });
  66137. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66138. /**
  66139. * Gets if the current filter is set to Poisson Sampling.
  66140. */
  66141. get: function () {
  66142. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66143. },
  66144. /**
  66145. * Sets the current filter to Poisson Sampling.
  66146. */
  66147. set: function (value) {
  66148. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66149. return;
  66150. }
  66151. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66157. /**
  66158. * Gets if the current filter is set to VSM.
  66159. * DEPRECATED. Should use useExponentialShadowMap instead.
  66160. */
  66161. get: function () {
  66162. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66163. return this.useExponentialShadowMap;
  66164. },
  66165. /**
  66166. * Sets the current filter is to VSM.
  66167. * DEPRECATED. Should use useExponentialShadowMap instead.
  66168. */
  66169. set: function (value) {
  66170. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66171. this.useExponentialShadowMap = value;
  66172. },
  66173. enumerable: true,
  66174. configurable: true
  66175. });
  66176. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66177. /**
  66178. * Gets if the current filter is set to blurred VSM.
  66179. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66180. */
  66181. get: function () {
  66182. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66183. return this.useBlurExponentialShadowMap;
  66184. },
  66185. /**
  66186. * Sets the current filter is to blurred VSM.
  66187. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66188. */
  66189. set: function (value) {
  66190. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66191. this.useBlurExponentialShadowMap = value;
  66192. },
  66193. enumerable: true,
  66194. configurable: true
  66195. });
  66196. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66197. /**
  66198. * Gets if the current filter is set to ESM.
  66199. */
  66200. get: function () {
  66201. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66202. },
  66203. /**
  66204. * Sets the current filter is to ESM.
  66205. */
  66206. set: function (value) {
  66207. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66208. return;
  66209. }
  66210. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66211. },
  66212. enumerable: true,
  66213. configurable: true
  66214. });
  66215. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66216. /**
  66217. * Gets if the current filter is set to filtered ESM.
  66218. */
  66219. get: function () {
  66220. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66221. },
  66222. /**
  66223. * Gets if the current filter is set to filtered ESM.
  66224. */
  66225. set: function (value) {
  66226. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66227. return;
  66228. }
  66229. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66230. },
  66231. enumerable: true,
  66232. configurable: true
  66233. });
  66234. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66235. /**
  66236. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66237. * exponential to prevent steep falloff artifacts).
  66238. */
  66239. get: function () {
  66240. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66241. },
  66242. /**
  66243. * Sets the current filter to "close ESM" (using the inverse of the
  66244. * exponential to prevent steep falloff artifacts).
  66245. */
  66246. set: function (value) {
  66247. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66248. return;
  66249. }
  66250. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66251. },
  66252. enumerable: true,
  66253. configurable: true
  66254. });
  66255. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66256. /**
  66257. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66258. * exponential to prevent steep falloff artifacts).
  66259. */
  66260. get: function () {
  66261. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66262. },
  66263. /**
  66264. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66265. * exponential to prevent steep falloff artifacts).
  66266. */
  66267. set: function (value) {
  66268. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66269. return;
  66270. }
  66271. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66272. },
  66273. enumerable: true,
  66274. configurable: true
  66275. });
  66276. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66277. /**
  66278. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66279. */
  66280. get: function () {
  66281. return this.filter === ShadowGenerator.FILTER_PCF;
  66282. },
  66283. /**
  66284. * Sets the current filter to "PCF" (percentage closer filtering).
  66285. */
  66286. set: function (value) {
  66287. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66288. return;
  66289. }
  66290. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66291. },
  66292. enumerable: true,
  66293. configurable: true
  66294. });
  66295. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66296. /**
  66297. * Gets the PCF or PCSS Quality.
  66298. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66299. */
  66300. get: function () {
  66301. return this._filteringQuality;
  66302. },
  66303. /**
  66304. * Sets the PCF or PCSS Quality.
  66305. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66306. */
  66307. set: function (filteringQuality) {
  66308. this._filteringQuality = filteringQuality;
  66309. },
  66310. enumerable: true,
  66311. configurable: true
  66312. });
  66313. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66314. /**
  66315. * Gets if the current filter is set to "PCSS" (contact hardening).
  66316. */
  66317. get: function () {
  66318. return this.filter === ShadowGenerator.FILTER_PCSS;
  66319. },
  66320. /**
  66321. * Sets the current filter to "PCSS" (contact hardening).
  66322. */
  66323. set: function (value) {
  66324. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66325. return;
  66326. }
  66327. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66328. },
  66329. enumerable: true,
  66330. configurable: true
  66331. });
  66332. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66333. /**
  66334. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66335. * Using a ratio helps keeping shape stability independently of the map size.
  66336. *
  66337. * It does not account for the light projection as it was having too much
  66338. * instability during the light setup or during light position changes.
  66339. *
  66340. * Only valid if useContactHardeningShadow is true.
  66341. */
  66342. get: function () {
  66343. return this._contactHardeningLightSizeUVRatio;
  66344. },
  66345. /**
  66346. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66347. * Using a ratio helps keeping shape stability independently of the map size.
  66348. *
  66349. * It does not account for the light projection as it was having too much
  66350. * instability during the light setup or during light position changes.
  66351. *
  66352. * Only valid if useContactHardeningShadow is true.
  66353. */
  66354. set: function (contactHardeningLightSizeUVRatio) {
  66355. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66356. },
  66357. enumerable: true,
  66358. configurable: true
  66359. });
  66360. /**
  66361. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66362. * 0 means strongest and 1 would means no shadow.
  66363. * @returns the darkness.
  66364. */
  66365. ShadowGenerator.prototype.getDarkness = function () {
  66366. return this._darkness;
  66367. };
  66368. /**
  66369. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66370. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66371. * @returns the shadow generator allowing fluent coding.
  66372. */
  66373. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66374. if (darkness >= 1.0)
  66375. this._darkness = 1.0;
  66376. else if (darkness <= 0.0)
  66377. this._darkness = 0.0;
  66378. else
  66379. this._darkness = darkness;
  66380. return this;
  66381. };
  66382. /**
  66383. * Sets the ability to have transparent shadow (boolean).
  66384. * @param transparent True if transparent else False
  66385. * @returns the shadow generator allowing fluent coding
  66386. */
  66387. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66388. this._transparencyShadow = transparent;
  66389. return this;
  66390. };
  66391. /**
  66392. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66393. * @returns The render target texture if present otherwise, null
  66394. */
  66395. ShadowGenerator.prototype.getShadowMap = function () {
  66396. return this._shadowMap;
  66397. };
  66398. /**
  66399. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66400. * @returns The render target texture if the shadow map is present otherwise, null
  66401. */
  66402. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66403. if (this._shadowMap2) {
  66404. return this._shadowMap2;
  66405. }
  66406. return this._shadowMap;
  66407. };
  66408. /**
  66409. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66410. * @param mesh Mesh to add
  66411. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66412. * @returns the Shadow Generator itself
  66413. */
  66414. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66415. if (includeDescendants === void 0) { includeDescendants = true; }
  66416. if (!this._shadowMap) {
  66417. return this;
  66418. }
  66419. if (!this._shadowMap.renderList) {
  66420. this._shadowMap.renderList = [];
  66421. }
  66422. this._shadowMap.renderList.push(mesh);
  66423. if (includeDescendants) {
  66424. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66425. }
  66426. return this;
  66427. var _a;
  66428. };
  66429. /**
  66430. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66431. * @param mesh Mesh to remove
  66432. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66433. * @returns the Shadow Generator itself
  66434. */
  66435. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66436. if (includeDescendants === void 0) { includeDescendants = true; }
  66437. if (!this._shadowMap || !this._shadowMap.renderList) {
  66438. return this;
  66439. }
  66440. var index = this._shadowMap.renderList.indexOf(mesh);
  66441. if (index !== -1) {
  66442. this._shadowMap.renderList.splice(index, 1);
  66443. }
  66444. if (includeDescendants) {
  66445. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66446. var child = _a[_i];
  66447. this.removeShadowCaster(child);
  66448. }
  66449. }
  66450. return this;
  66451. };
  66452. /**
  66453. * Returns the associated light object.
  66454. * @returns the light generating the shadow
  66455. */
  66456. ShadowGenerator.prototype.getLight = function () {
  66457. return this._light;
  66458. };
  66459. ShadowGenerator.prototype._initializeGenerator = function () {
  66460. this._light._markMeshesAsLightDirty();
  66461. this._initializeShadowMap();
  66462. };
  66463. ShadowGenerator.prototype._initializeShadowMap = function () {
  66464. var _this = this;
  66465. // Render target
  66466. var engine = this._scene.getEngine();
  66467. if (engine.webGLVersion > 1) {
  66468. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66469. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66470. }
  66471. else {
  66472. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66473. }
  66474. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66475. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66476. this._shadowMap.anisotropicFilteringLevel = 1;
  66477. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66478. this._shadowMap.renderParticles = false;
  66479. this._shadowMap.ignoreCameraViewport = true;
  66480. // Record Face Index before render.
  66481. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66482. _this._currentFaceIndex = faceIndex;
  66483. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66484. engine.setColorWrite(false);
  66485. }
  66486. });
  66487. // Custom render function.
  66488. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66489. // Blur if required afer render.
  66490. this._shadowMap.onAfterUnbindObservable.add(function () {
  66491. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66492. engine.setColorWrite(true);
  66493. }
  66494. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66495. return;
  66496. }
  66497. var shadowMap = _this.getShadowMapForRendering();
  66498. if (shadowMap) {
  66499. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66500. }
  66501. });
  66502. // Clear according to the chosen filter.
  66503. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66504. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66505. this._shadowMap.onClearObservable.add(function (engine) {
  66506. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66507. engine.clear(clearOne, false, true, false);
  66508. }
  66509. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66510. engine.clear(clearZero, true, true, false);
  66511. }
  66512. else {
  66513. engine.clear(clearOne, true, true, false);
  66514. }
  66515. });
  66516. };
  66517. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66518. var _this = this;
  66519. var engine = this._scene.getEngine();
  66520. var targetSize = this._mapSize / this.blurScale;
  66521. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66522. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66523. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66524. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66525. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66526. }
  66527. if (this.useKernelBlur) {
  66528. 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);
  66529. this._kernelBlurXPostprocess.width = targetSize;
  66530. this._kernelBlurXPostprocess.height = targetSize;
  66531. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66532. effect.setTexture("textureSampler", _this._shadowMap);
  66533. });
  66534. 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);
  66535. this._kernelBlurXPostprocess.autoClear = false;
  66536. this._kernelBlurYPostprocess.autoClear = false;
  66537. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66538. this._kernelBlurXPostprocess.packedFloat = true;
  66539. this._kernelBlurYPostprocess.packedFloat = true;
  66540. }
  66541. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66542. }
  66543. else {
  66544. 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);
  66545. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66546. effect.setFloat2("screenSize", targetSize, targetSize);
  66547. effect.setTexture("textureSampler", _this._shadowMap);
  66548. });
  66549. this._boxBlurPostprocess.autoClear = false;
  66550. this._blurPostProcesses = [this._boxBlurPostprocess];
  66551. }
  66552. };
  66553. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66554. var index;
  66555. var engine = this._scene.getEngine();
  66556. if (depthOnlySubMeshes.length) {
  66557. engine.setColorWrite(false);
  66558. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66559. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66560. }
  66561. engine.setColorWrite(true);
  66562. }
  66563. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66564. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66565. }
  66566. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66567. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66568. }
  66569. if (this._transparencyShadow) {
  66570. for (index = 0; index < transparentSubMeshes.length; index++) {
  66571. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66572. }
  66573. }
  66574. };
  66575. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66576. var _this = this;
  66577. var mesh = subMesh.getRenderingMesh();
  66578. var scene = this._scene;
  66579. var engine = scene.getEngine();
  66580. var material = subMesh.getMaterial();
  66581. if (!material) {
  66582. return;
  66583. }
  66584. // Culling
  66585. engine.setState(material.backFaceCulling);
  66586. // Managing instances
  66587. var batch = mesh._getInstancesRenderList(subMesh._id);
  66588. if (batch.mustReturn) {
  66589. return;
  66590. }
  66591. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66592. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66593. engine.enableEffect(this._effect);
  66594. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66595. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66596. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66597. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66598. this._effect.setVector3("lightData", this._cachedDirection);
  66599. }
  66600. else {
  66601. this._effect.setVector3("lightData", this._cachedPosition);
  66602. }
  66603. if (scene.activeCamera) {
  66604. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66605. }
  66606. // Alpha test
  66607. if (material && material.needAlphaTesting()) {
  66608. var alphaTexture = material.getAlphaTestTexture();
  66609. if (alphaTexture) {
  66610. this._effect.setTexture("diffuseSampler", alphaTexture);
  66611. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66612. }
  66613. }
  66614. // Bones
  66615. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66616. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66617. }
  66618. // Morph targets
  66619. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66620. if (this.forceBackFacesOnly) {
  66621. engine.setState(true, 0, false, true);
  66622. }
  66623. // Draw
  66624. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66625. if (this.forceBackFacesOnly) {
  66626. engine.setState(true, 0, false, false);
  66627. }
  66628. }
  66629. else {
  66630. // Need to reset refresh rate of the shadowMap
  66631. if (this._shadowMap) {
  66632. this._shadowMap.resetRefreshCounter();
  66633. }
  66634. }
  66635. };
  66636. ShadowGenerator.prototype._applyFilterValues = function () {
  66637. if (!this._shadowMap) {
  66638. return;
  66639. }
  66640. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66641. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66642. }
  66643. else {
  66644. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66645. }
  66646. };
  66647. /**
  66648. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66649. * @param onCompiled Callback triggered at the and of the effects compilation
  66650. * @param options Sets of optional options forcing the compilation with different modes
  66651. */
  66652. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66653. var _this = this;
  66654. var localOptions = __assign({ useInstances: false }, options);
  66655. var shadowMap = this.getShadowMap();
  66656. if (!shadowMap) {
  66657. if (onCompiled) {
  66658. onCompiled(this);
  66659. }
  66660. return;
  66661. }
  66662. var renderList = shadowMap.renderList;
  66663. if (!renderList) {
  66664. if (onCompiled) {
  66665. onCompiled(this);
  66666. }
  66667. return;
  66668. }
  66669. var subMeshes = new Array();
  66670. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66671. var mesh = renderList_1[_i];
  66672. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66673. }
  66674. if (subMeshes.length === 0) {
  66675. if (onCompiled) {
  66676. onCompiled(this);
  66677. }
  66678. return;
  66679. }
  66680. var currentIndex = 0;
  66681. var checkReady = function () {
  66682. if (!_this._scene || !_this._scene.getEngine()) {
  66683. return;
  66684. }
  66685. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66686. currentIndex++;
  66687. if (currentIndex >= subMeshes.length) {
  66688. if (onCompiled) {
  66689. onCompiled(_this);
  66690. }
  66691. return;
  66692. }
  66693. }
  66694. setTimeout(checkReady, 16);
  66695. };
  66696. checkReady();
  66697. };
  66698. /**
  66699. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66700. * @param options Sets of optional options forcing the compilation with different modes
  66701. * @returns A promise that resolves when the compilation completes
  66702. */
  66703. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66704. var _this = this;
  66705. return new Promise(function (resolve) {
  66706. _this.forceCompilation(function () {
  66707. resolve();
  66708. }, options);
  66709. });
  66710. };
  66711. /**
  66712. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66713. * @param subMesh The submesh we want to render in the shadow map
  66714. * @param useInstances Defines wether will draw in the map using instances
  66715. * @returns true if ready otherwise, false
  66716. */
  66717. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66718. var defines = [];
  66719. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66720. defines.push("#define FLOAT");
  66721. }
  66722. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66723. defines.push("#define ESM");
  66724. }
  66725. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66726. defines.push("#define DEPTHTEXTURE");
  66727. }
  66728. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66729. var mesh = subMesh.getMesh();
  66730. var material = subMesh.getMaterial();
  66731. // Normal bias.
  66732. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66733. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66734. defines.push("#define NORMAL");
  66735. if (mesh.nonUniformScaling) {
  66736. defines.push("#define NONUNIFORMSCALING");
  66737. }
  66738. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66739. defines.push("#define DIRECTIONINLIGHTDATA");
  66740. }
  66741. }
  66742. // Alpha test
  66743. if (material && material.needAlphaTesting()) {
  66744. var alphaTexture = material.getAlphaTestTexture();
  66745. if (alphaTexture) {
  66746. defines.push("#define ALPHATEST");
  66747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66748. attribs.push(BABYLON.VertexBuffer.UVKind);
  66749. defines.push("#define UV1");
  66750. }
  66751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66752. if (alphaTexture.coordinatesIndex === 1) {
  66753. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66754. defines.push("#define UV2");
  66755. }
  66756. }
  66757. }
  66758. }
  66759. // Bones
  66760. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66763. if (mesh.numBoneInfluencers > 4) {
  66764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66766. }
  66767. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66768. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66769. }
  66770. else {
  66771. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66772. }
  66773. // Morph targets
  66774. var manager = mesh.morphTargetManager;
  66775. var morphInfluencers = 0;
  66776. if (manager) {
  66777. if (manager.numInfluencers > 0) {
  66778. defines.push("#define MORPHTARGETS");
  66779. morphInfluencers = manager.numInfluencers;
  66780. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66781. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66782. }
  66783. }
  66784. // Instances
  66785. if (useInstances) {
  66786. defines.push("#define INSTANCES");
  66787. attribs.push("world0");
  66788. attribs.push("world1");
  66789. attribs.push("world2");
  66790. attribs.push("world3");
  66791. }
  66792. // Get correct effect
  66793. var join = defines.join("\n");
  66794. if (this._cachedDefines !== join) {
  66795. this._cachedDefines = join;
  66796. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66797. }
  66798. if (!this._effect.isReady()) {
  66799. return false;
  66800. }
  66801. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66802. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66803. this._initializeBlurRTTAndPostProcesses();
  66804. }
  66805. }
  66806. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66807. return false;
  66808. }
  66809. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66810. return false;
  66811. }
  66812. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66813. return false;
  66814. }
  66815. return true;
  66816. };
  66817. /**
  66818. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66819. * @param defines Defines of the material we want to update
  66820. * @param lightIndex Index of the light in the enabled light list of the material
  66821. */
  66822. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66823. var scene = this._scene;
  66824. var light = this._light;
  66825. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66826. return;
  66827. }
  66828. defines["SHADOW" + lightIndex] = true;
  66829. if (this.useContactHardeningShadow) {
  66830. defines["SHADOWPCSS" + lightIndex] = true;
  66831. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66832. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66833. }
  66834. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66835. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66836. }
  66837. // else default to high.
  66838. }
  66839. if (this.usePercentageCloserFiltering) {
  66840. defines["SHADOWPCF" + lightIndex] = true;
  66841. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66842. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66843. }
  66844. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66845. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66846. }
  66847. // else default to high.
  66848. }
  66849. else if (this.usePoissonSampling) {
  66850. defines["SHADOWPOISSON" + lightIndex] = true;
  66851. }
  66852. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66853. defines["SHADOWESM" + lightIndex] = true;
  66854. }
  66855. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66856. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66857. }
  66858. if (light.needCube()) {
  66859. defines["SHADOWCUBE" + lightIndex] = true;
  66860. }
  66861. };
  66862. /**
  66863. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66864. * defined in the generator but impacting the effect).
  66865. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66866. * @param effect The effect we are binfing the information for
  66867. */
  66868. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66869. var light = this._light;
  66870. var scene = this._scene;
  66871. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66872. return;
  66873. }
  66874. var camera = scene.activeCamera;
  66875. if (!camera) {
  66876. return;
  66877. }
  66878. var shadowMap = this.getShadowMap();
  66879. if (!shadowMap) {
  66880. return;
  66881. }
  66882. if (!light.needCube()) {
  66883. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66884. }
  66885. // Only PCF uses depth stencil texture.
  66886. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66887. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66888. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66889. }
  66890. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66891. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66892. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66893. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66894. }
  66895. else {
  66896. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66897. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66898. }
  66899. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66900. };
  66901. /**
  66902. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66903. * (eq to shadow prjection matrix * light transform matrix)
  66904. * @returns The transform matrix used to create the shadow map
  66905. */
  66906. ShadowGenerator.prototype.getTransformMatrix = function () {
  66907. var scene = this._scene;
  66908. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66909. return this._transformMatrix;
  66910. }
  66911. this._currentRenderID = scene.getRenderId();
  66912. this._currentFaceIndexCache = this._currentFaceIndex;
  66913. var lightPosition = this._light.position;
  66914. if (this._light.computeTransformedInformation()) {
  66915. lightPosition = this._light.transformedPosition;
  66916. }
  66917. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66918. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66919. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66920. }
  66921. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66922. this._cachedPosition.copyFrom(lightPosition);
  66923. this._cachedDirection.copyFrom(this._lightDirection);
  66924. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66925. var shadowMap = this.getShadowMap();
  66926. if (shadowMap) {
  66927. var renderList = shadowMap.renderList;
  66928. if (renderList) {
  66929. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66930. }
  66931. }
  66932. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66933. }
  66934. return this._transformMatrix;
  66935. };
  66936. /**
  66937. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66938. * Cube and 2D textures for instance.
  66939. */
  66940. ShadowGenerator.prototype.recreateShadowMap = function () {
  66941. var shadowMap = this._shadowMap;
  66942. if (!shadowMap) {
  66943. return;
  66944. }
  66945. // Track render list.
  66946. var renderList = shadowMap.renderList;
  66947. // Clean up existing data.
  66948. this._disposeRTTandPostProcesses();
  66949. // Reinitializes.
  66950. this._initializeGenerator();
  66951. // Reaffect the filter to ensure a correct fallback if necessary.
  66952. this.filter = this.filter;
  66953. // Reaffect the filter.
  66954. this._applyFilterValues();
  66955. // Reaffect Render List.
  66956. this._shadowMap.renderList = renderList;
  66957. };
  66958. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66959. if (this._shadowMap2) {
  66960. this._shadowMap2.dispose();
  66961. this._shadowMap2 = null;
  66962. }
  66963. if (this._boxBlurPostprocess) {
  66964. this._boxBlurPostprocess.dispose();
  66965. this._boxBlurPostprocess = null;
  66966. }
  66967. if (this._kernelBlurXPostprocess) {
  66968. this._kernelBlurXPostprocess.dispose();
  66969. this._kernelBlurXPostprocess = null;
  66970. }
  66971. if (this._kernelBlurYPostprocess) {
  66972. this._kernelBlurYPostprocess.dispose();
  66973. this._kernelBlurYPostprocess = null;
  66974. }
  66975. this._blurPostProcesses = [];
  66976. };
  66977. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66978. if (this._shadowMap) {
  66979. this._shadowMap.dispose();
  66980. this._shadowMap = null;
  66981. }
  66982. this._disposeBlurPostProcesses();
  66983. };
  66984. /**
  66985. * Disposes the ShadowGenerator.
  66986. * Returns nothing.
  66987. */
  66988. ShadowGenerator.prototype.dispose = function () {
  66989. this._disposeRTTandPostProcesses();
  66990. if (this._light) {
  66991. this._light._shadowGenerator = null;
  66992. this._light._markMeshesAsLightDirty();
  66993. }
  66994. };
  66995. /**
  66996. * Serializes the shadow generator setup to a json object.
  66997. * @returns The serialized JSON object
  66998. */
  66999. ShadowGenerator.prototype.serialize = function () {
  67000. var serializationObject = {};
  67001. var shadowMap = this.getShadowMap();
  67002. if (!shadowMap) {
  67003. return serializationObject;
  67004. }
  67005. serializationObject.lightId = this._light.id;
  67006. serializationObject.mapSize = shadowMap.getRenderSize();
  67007. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67008. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67009. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67010. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67011. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67012. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67013. serializationObject.depthScale = this.depthScale;
  67014. serializationObject.darkness = this.getDarkness();
  67015. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67016. serializationObject.blurKernel = this.blurKernel;
  67017. serializationObject.blurScale = this.blurScale;
  67018. serializationObject.useKernelBlur = this.useKernelBlur;
  67019. serializationObject.transparencyShadow = this._transparencyShadow;
  67020. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67021. serializationObject.bias = this.bias;
  67022. serializationObject.normalBias = this.normalBias;
  67023. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67024. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67025. serializationObject.filteringQuality = this.filteringQuality;
  67026. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67027. serializationObject.renderList = [];
  67028. if (shadowMap.renderList) {
  67029. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67030. var mesh = shadowMap.renderList[meshIndex];
  67031. serializationObject.renderList.push(mesh.id);
  67032. }
  67033. }
  67034. return serializationObject;
  67035. };
  67036. /**
  67037. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67038. * @param parsedShadowGenerator The JSON object to parse
  67039. * @param scene The scene to create the shadow map for
  67040. * @returns The parsed shadow generator
  67041. */
  67042. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67043. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67044. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67045. var shadowMap = shadowGenerator.getShadowMap();
  67046. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67047. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67048. meshes.forEach(function (mesh) {
  67049. if (!shadowMap) {
  67050. return;
  67051. }
  67052. if (!shadowMap.renderList) {
  67053. shadowMap.renderList = [];
  67054. }
  67055. shadowMap.renderList.push(mesh);
  67056. });
  67057. }
  67058. if (parsedShadowGenerator.usePoissonSampling) {
  67059. shadowGenerator.usePoissonSampling = true;
  67060. }
  67061. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67062. shadowGenerator.useExponentialShadowMap = true;
  67063. }
  67064. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67065. shadowGenerator.useBlurExponentialShadowMap = true;
  67066. }
  67067. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67068. shadowGenerator.useCloseExponentialShadowMap = true;
  67069. }
  67070. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67071. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67072. }
  67073. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67074. shadowGenerator.usePercentageCloserFiltering = true;
  67075. }
  67076. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67077. shadowGenerator.useContactHardeningShadow = true;
  67078. }
  67079. if (parsedShadowGenerator.filteringQuality) {
  67080. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67081. }
  67082. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67083. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67084. }
  67085. // Backward compat
  67086. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67087. shadowGenerator.useExponentialShadowMap = true;
  67088. }
  67089. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67090. shadowGenerator.useBlurExponentialShadowMap = true;
  67091. }
  67092. if (parsedShadowGenerator.depthScale) {
  67093. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67094. }
  67095. if (parsedShadowGenerator.blurScale) {
  67096. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67097. }
  67098. if (parsedShadowGenerator.blurBoxOffset) {
  67099. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67100. }
  67101. if (parsedShadowGenerator.useKernelBlur) {
  67102. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67103. }
  67104. if (parsedShadowGenerator.blurKernel) {
  67105. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67106. }
  67107. if (parsedShadowGenerator.bias !== undefined) {
  67108. shadowGenerator.bias = parsedShadowGenerator.bias;
  67109. }
  67110. if (parsedShadowGenerator.normalBias !== undefined) {
  67111. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67112. }
  67113. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67114. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67115. }
  67116. if (parsedShadowGenerator.darkness) {
  67117. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67118. }
  67119. if (parsedShadowGenerator.transparencyShadow) {
  67120. shadowGenerator.setTransparencyShadow(true);
  67121. }
  67122. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67123. return shadowGenerator;
  67124. };
  67125. /**
  67126. * Shadow generator mode None: no filtering applied.
  67127. */
  67128. ShadowGenerator.FILTER_NONE = 0;
  67129. /**
  67130. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67131. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67132. */
  67133. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67134. /**
  67135. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67136. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67137. */
  67138. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67139. /**
  67140. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67141. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67142. */
  67143. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67144. /**
  67145. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67146. * edge artifacts on steep falloff.
  67147. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67148. */
  67149. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67150. /**
  67151. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67152. * edge artifacts on steep falloff.
  67153. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67154. */
  67155. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67156. /**
  67157. * Shadow generator mode PCF: Percentage Closer Filtering
  67158. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67159. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67160. */
  67161. ShadowGenerator.FILTER_PCF = 6;
  67162. /**
  67163. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67164. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67165. * Contact Hardening
  67166. */
  67167. ShadowGenerator.FILTER_PCSS = 7;
  67168. /**
  67169. * Reserved for PCF and PCSS
  67170. * Highest Quality.
  67171. *
  67172. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67173. *
  67174. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67175. */
  67176. ShadowGenerator.QUALITY_HIGH = 0;
  67177. /**
  67178. * Reserved for PCF and PCSS
  67179. * Good tradeoff for quality/perf cross devices
  67180. *
  67181. * Execute PCF on a 3*3 kernel.
  67182. *
  67183. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67184. */
  67185. ShadowGenerator.QUALITY_MEDIUM = 1;
  67186. /**
  67187. * Reserved for PCF and PCSS
  67188. * The lowest quality but the fastest.
  67189. *
  67190. * Execute PCF on a 1*1 kernel.
  67191. *
  67192. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67193. */
  67194. ShadowGenerator.QUALITY_LOW = 2;
  67195. return ShadowGenerator;
  67196. }());
  67197. BABYLON.ShadowGenerator = ShadowGenerator;
  67198. })(BABYLON || (BABYLON = {}));
  67199. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67200. var BABYLON;
  67201. (function (BABYLON) {
  67202. var DefaultLoadingScreen = /** @class */ (function () {
  67203. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67204. if (_loadingText === void 0) { _loadingText = ""; }
  67205. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67206. var _this = this;
  67207. this._renderingCanvas = _renderingCanvas;
  67208. this._loadingText = _loadingText;
  67209. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67210. // Resize
  67211. this._resizeLoadingUI = function () {
  67212. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67213. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67214. if (!_this._loadingDiv) {
  67215. return;
  67216. }
  67217. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67218. _this._loadingDiv.style.left = canvasRect.left + "px";
  67219. _this._loadingDiv.style.top = canvasRect.top + "px";
  67220. _this._loadingDiv.style.width = canvasRect.width + "px";
  67221. _this._loadingDiv.style.height = canvasRect.height + "px";
  67222. };
  67223. }
  67224. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67225. if (this._loadingDiv) {
  67226. // Do not add a loading screen if there is already one
  67227. return;
  67228. }
  67229. this._loadingDiv = document.createElement("div");
  67230. this._loadingDiv.id = "babylonjsLoadingDiv";
  67231. this._loadingDiv.style.opacity = "0";
  67232. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67233. this._loadingDiv.style.pointerEvents = "none";
  67234. // Loading text
  67235. this._loadingTextDiv = document.createElement("div");
  67236. this._loadingTextDiv.style.position = "absolute";
  67237. this._loadingTextDiv.style.left = "0";
  67238. this._loadingTextDiv.style.top = "50%";
  67239. this._loadingTextDiv.style.marginTop = "80px";
  67240. this._loadingTextDiv.style.width = "100%";
  67241. this._loadingTextDiv.style.height = "20px";
  67242. this._loadingTextDiv.style.fontFamily = "Arial";
  67243. this._loadingTextDiv.style.fontSize = "14px";
  67244. this._loadingTextDiv.style.color = "white";
  67245. this._loadingTextDiv.style.textAlign = "center";
  67246. this._loadingTextDiv.innerHTML = "Loading";
  67247. this._loadingDiv.appendChild(this._loadingTextDiv);
  67248. //set the predefined text
  67249. this._loadingTextDiv.innerHTML = this._loadingText;
  67250. // Generating keyframes
  67251. var style = document.createElement('style');
  67252. style.type = 'text/css';
  67253. 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 }";
  67254. style.innerHTML = keyFrames;
  67255. document.getElementsByTagName('head')[0].appendChild(style);
  67256. // Loading img
  67257. var imgBack = new Image();
  67258. 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";
  67259. imgBack.style.position = "absolute";
  67260. imgBack.style.left = "50%";
  67261. imgBack.style.top = "50%";
  67262. imgBack.style.marginLeft = "-60px";
  67263. imgBack.style.marginTop = "-60px";
  67264. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67265. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67266. imgBack.style.transformOrigin = "50% 50%";
  67267. imgBack.style.webkitTransformOrigin = "50% 50%";
  67268. this._loadingDiv.appendChild(imgBack);
  67269. this._resizeLoadingUI();
  67270. window.addEventListener("resize", this._resizeLoadingUI);
  67271. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67272. document.body.appendChild(this._loadingDiv);
  67273. this._loadingDiv.style.opacity = "1";
  67274. };
  67275. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67276. var _this = this;
  67277. if (!this._loadingDiv) {
  67278. return;
  67279. }
  67280. var onTransitionEnd = function () {
  67281. if (!_this._loadingDiv) {
  67282. return;
  67283. }
  67284. document.body.removeChild(_this._loadingDiv);
  67285. window.removeEventListener("resize", _this._resizeLoadingUI);
  67286. _this._loadingDiv = null;
  67287. };
  67288. this._loadingDiv.style.opacity = "0";
  67289. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67290. };
  67291. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67292. set: function (text) {
  67293. this._loadingText = text;
  67294. if (this._loadingTextDiv) {
  67295. this._loadingTextDiv.innerHTML = this._loadingText;
  67296. }
  67297. },
  67298. enumerable: true,
  67299. configurable: true
  67300. });
  67301. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67302. get: function () {
  67303. return this._loadingDivBackgroundColor;
  67304. },
  67305. set: function (color) {
  67306. this._loadingDivBackgroundColor = color;
  67307. if (!this._loadingDiv) {
  67308. return;
  67309. }
  67310. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67311. },
  67312. enumerable: true,
  67313. configurable: true
  67314. });
  67315. return DefaultLoadingScreen;
  67316. }());
  67317. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67318. })(BABYLON || (BABYLON = {}));
  67319. //# sourceMappingURL=babylon.loadingScreen.js.map
  67320. var BABYLON;
  67321. (function (BABYLON) {
  67322. var SceneLoaderProgressEvent = /** @class */ (function () {
  67323. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67324. this.lengthComputable = lengthComputable;
  67325. this.loaded = loaded;
  67326. this.total = total;
  67327. }
  67328. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67329. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67330. };
  67331. return SceneLoaderProgressEvent;
  67332. }());
  67333. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67334. var SceneLoader = /** @class */ (function () {
  67335. function SceneLoader() {
  67336. }
  67337. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67338. get: function () {
  67339. return 0;
  67340. },
  67341. enumerable: true,
  67342. configurable: true
  67343. });
  67344. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67345. get: function () {
  67346. return 1;
  67347. },
  67348. enumerable: true,
  67349. configurable: true
  67350. });
  67351. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67352. get: function () {
  67353. return 2;
  67354. },
  67355. enumerable: true,
  67356. configurable: true
  67357. });
  67358. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67359. get: function () {
  67360. return 3;
  67361. },
  67362. enumerable: true,
  67363. configurable: true
  67364. });
  67365. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67366. get: function () {
  67367. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67368. },
  67369. set: function (value) {
  67370. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67371. },
  67372. enumerable: true,
  67373. configurable: true
  67374. });
  67375. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67376. get: function () {
  67377. return SceneLoader._ShowLoadingScreen;
  67378. },
  67379. set: function (value) {
  67380. SceneLoader._ShowLoadingScreen = value;
  67381. },
  67382. enumerable: true,
  67383. configurable: true
  67384. });
  67385. Object.defineProperty(SceneLoader, "loggingLevel", {
  67386. get: function () {
  67387. return SceneLoader._loggingLevel;
  67388. },
  67389. set: function (value) {
  67390. SceneLoader._loggingLevel = value;
  67391. },
  67392. enumerable: true,
  67393. configurable: true
  67394. });
  67395. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67396. get: function () {
  67397. return SceneLoader._CleanBoneMatrixWeights;
  67398. },
  67399. set: function (value) {
  67400. SceneLoader._CleanBoneMatrixWeights = value;
  67401. },
  67402. enumerable: true,
  67403. configurable: true
  67404. });
  67405. SceneLoader._getDefaultPlugin = function () {
  67406. return SceneLoader._registeredPlugins[".babylon"];
  67407. };
  67408. SceneLoader._getPluginForExtension = function (extension) {
  67409. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67410. if (registeredPlugin) {
  67411. return registeredPlugin;
  67412. }
  67413. 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");
  67414. return SceneLoader._getDefaultPlugin();
  67415. };
  67416. SceneLoader._getPluginForDirectLoad = function (data) {
  67417. for (var extension in SceneLoader._registeredPlugins) {
  67418. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67419. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67420. return SceneLoader._registeredPlugins[extension];
  67421. }
  67422. }
  67423. return SceneLoader._getDefaultPlugin();
  67424. };
  67425. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67426. if (sceneFilename.name) {
  67427. sceneFilename = sceneFilename.name;
  67428. }
  67429. var queryStringPosition = sceneFilename.indexOf("?");
  67430. if (queryStringPosition !== -1) {
  67431. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67432. }
  67433. var dotPosition = sceneFilename.lastIndexOf(".");
  67434. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67435. return SceneLoader._getPluginForExtension(extension);
  67436. };
  67437. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67438. SceneLoader._getDirectLoad = function (sceneFilename) {
  67439. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67440. return sceneFilename.substr(5);
  67441. }
  67442. return null;
  67443. };
  67444. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67445. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67446. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67447. var plugin;
  67448. if (registeredPlugin.plugin.createPlugin) {
  67449. plugin = registeredPlugin.plugin.createPlugin();
  67450. }
  67451. else {
  67452. plugin = registeredPlugin.plugin;
  67453. }
  67454. var useArrayBuffer = registeredPlugin.isBinary;
  67455. var database;
  67456. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67457. var dataCallback = function (data, responseURL) {
  67458. if (scene.isDisposed) {
  67459. onError("Scene has been disposed");
  67460. return;
  67461. }
  67462. scene.database = database;
  67463. onSuccess(plugin, data, responseURL);
  67464. };
  67465. var request = null;
  67466. var pluginDisposed = false;
  67467. var onDisposeObservable = plugin.onDisposeObservable;
  67468. if (onDisposeObservable) {
  67469. onDisposeObservable.add(function () {
  67470. pluginDisposed = true;
  67471. if (request) {
  67472. request.abort();
  67473. request = null;
  67474. }
  67475. onDispose();
  67476. });
  67477. }
  67478. var manifestChecked = function () {
  67479. if (pluginDisposed) {
  67480. return;
  67481. }
  67482. var url = rootUrl + sceneFilename;
  67483. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67484. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67485. } : undefined, database, useArrayBuffer, function (request, exception) {
  67486. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67487. });
  67488. };
  67489. if (directLoad) {
  67490. dataCallback(directLoad);
  67491. return plugin;
  67492. }
  67493. if (rootUrl.indexOf("file:") === -1) {
  67494. var engine = scene.getEngine();
  67495. var canUseOfflineSupport = engine.enableOfflineSupport;
  67496. if (canUseOfflineSupport) {
  67497. // Also check for exceptions
  67498. var exceptionFound = false;
  67499. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67500. var regex = _a[_i];
  67501. if (regex.test(rootUrl + sceneFilename)) {
  67502. exceptionFound = true;
  67503. break;
  67504. }
  67505. }
  67506. canUseOfflineSupport = !exceptionFound;
  67507. }
  67508. if (canUseOfflineSupport) {
  67509. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67510. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67511. }
  67512. else {
  67513. manifestChecked();
  67514. }
  67515. }
  67516. // Loading file from disk via input file or drag'n'drop
  67517. else {
  67518. var fileOrString = sceneFilename;
  67519. if (fileOrString.name) { // File
  67520. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67521. }
  67522. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67523. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67524. }
  67525. else {
  67526. onError("Unable to find file named " + sceneFilename);
  67527. }
  67528. }
  67529. return plugin;
  67530. };
  67531. // Public functions
  67532. SceneLoader.GetPluginForExtension = function (extension) {
  67533. return SceneLoader._getPluginForExtension(extension).plugin;
  67534. };
  67535. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67536. return !!SceneLoader._registeredPlugins[extension];
  67537. };
  67538. SceneLoader.RegisterPlugin = function (plugin) {
  67539. if (typeof plugin.extensions === "string") {
  67540. var extension = plugin.extensions;
  67541. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67542. plugin: plugin,
  67543. isBinary: false
  67544. };
  67545. }
  67546. else {
  67547. var extensions = plugin.extensions;
  67548. Object.keys(extensions).forEach(function (extension) {
  67549. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67550. plugin: plugin,
  67551. isBinary: extensions[extension].isBinary
  67552. };
  67553. });
  67554. }
  67555. };
  67556. /**
  67557. * Import meshes into a scene
  67558. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67559. * @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)
  67560. * @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)
  67561. * @param scene the instance of BABYLON.Scene to append to
  67562. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67563. * @param onProgress a callback with a progress event for each file being loaded
  67564. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67565. * @param pluginExtension the extension used to determine the plugin
  67566. * @returns The loaded plugin
  67567. */
  67568. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67569. if (sceneFilename === void 0) { sceneFilename = ""; }
  67570. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67571. if (onSuccess === void 0) { onSuccess = null; }
  67572. if (onProgress === void 0) { onProgress = null; }
  67573. if (onError === void 0) { onError = null; }
  67574. if (pluginExtension === void 0) { pluginExtension = null; }
  67575. if (!scene) {
  67576. BABYLON.Tools.Error("No scene available to import mesh to");
  67577. return null;
  67578. }
  67579. if (!sceneFilename) {
  67580. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67581. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67582. }
  67583. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67584. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67585. return null;
  67586. }
  67587. var loadingToken = {};
  67588. scene._addPendingData(loadingToken);
  67589. var disposeHandler = function () {
  67590. scene._removePendingData(loadingToken);
  67591. };
  67592. var errorHandler = function (message, exception) {
  67593. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67594. if (onError) {
  67595. onError(scene, errorMessage, exception);
  67596. }
  67597. else {
  67598. BABYLON.Tools.Error(errorMessage);
  67599. // should the exception be thrown?
  67600. }
  67601. disposeHandler();
  67602. };
  67603. var progressHandler = onProgress ? function (event) {
  67604. try {
  67605. onProgress(event);
  67606. }
  67607. catch (e) {
  67608. errorHandler("Error in onProgress callback", e);
  67609. }
  67610. } : undefined;
  67611. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67612. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67613. if (onSuccess) {
  67614. try {
  67615. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67616. }
  67617. catch (e) {
  67618. errorHandler("Error in onSuccess callback", e);
  67619. }
  67620. }
  67621. scene._removePendingData(loadingToken);
  67622. };
  67623. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67624. if (plugin.rewriteRootURL) {
  67625. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67626. }
  67627. if (sceneFilename === "") {
  67628. if (sceneFilename === "") {
  67629. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67630. }
  67631. }
  67632. if (plugin.importMesh) {
  67633. var syncedPlugin = plugin;
  67634. var meshes = new Array();
  67635. var particleSystems = new Array();
  67636. var skeletons = new Array();
  67637. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67638. return;
  67639. }
  67640. scene.loadingPluginName = plugin.name;
  67641. successHandler(meshes, particleSystems, skeletons, []);
  67642. }
  67643. else {
  67644. var asyncedPlugin = plugin;
  67645. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67646. scene.loadingPluginName = plugin.name;
  67647. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67648. }).catch(function (error) {
  67649. errorHandler(error.message, error);
  67650. });
  67651. }
  67652. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67653. };
  67654. /**
  67655. * Import meshes into a scene
  67656. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67657. * @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)
  67658. * @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)
  67659. * @param scene the instance of BABYLON.Scene to append to
  67660. * @param onProgress a callback with a progress event for each file being loaded
  67661. * @param pluginExtension the extension used to determine the plugin
  67662. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67663. */
  67664. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67665. if (sceneFilename === void 0) { sceneFilename = ""; }
  67666. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67667. if (onProgress === void 0) { onProgress = null; }
  67668. if (pluginExtension === void 0) { pluginExtension = null; }
  67669. return new Promise(function (resolve, reject) {
  67670. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67671. resolve({
  67672. meshes: meshes,
  67673. particleSystems: particleSystems,
  67674. skeletons: skeletons,
  67675. animationGroups: animationGroups
  67676. });
  67677. }, onProgress, function (scene, message, exception) {
  67678. reject(exception || new Error(message));
  67679. }, pluginExtension);
  67680. });
  67681. };
  67682. /**
  67683. * Load a scene
  67684. * @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)
  67685. * @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)
  67686. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67687. * @param onSuccess a callback with the scene when import succeeds
  67688. * @param onProgress a callback with a progress event for each file being loaded
  67689. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67690. * @param pluginExtension the extension used to determine the plugin
  67691. * @returns The loaded plugin
  67692. */
  67693. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67694. if (onSuccess === void 0) { onSuccess = null; }
  67695. if (onProgress === void 0) { onProgress = null; }
  67696. if (onError === void 0) { onError = null; }
  67697. if (pluginExtension === void 0) { pluginExtension = null; }
  67698. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67699. };
  67700. /**
  67701. * Load a scene
  67702. * @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)
  67703. * @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)
  67704. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67705. * @param onProgress a callback with a progress event for each file being loaded
  67706. * @param pluginExtension the extension used to determine the plugin
  67707. * @returns The loaded scene
  67708. */
  67709. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67710. if (onProgress === void 0) { onProgress = null; }
  67711. if (pluginExtension === void 0) { pluginExtension = null; }
  67712. return new Promise(function (resolve, reject) {
  67713. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67714. resolve(scene);
  67715. }, onProgress, function (scene, message, exception) {
  67716. reject(exception || new Error(message));
  67717. }, pluginExtension);
  67718. });
  67719. };
  67720. /**
  67721. * Append a scene
  67722. * @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)
  67723. * @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)
  67724. * @param scene is the instance of BABYLON.Scene to append to
  67725. * @param onSuccess a callback with the scene when import succeeds
  67726. * @param onProgress a callback with a progress event for each file being loaded
  67727. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67728. * @param pluginExtension the extension used to determine the plugin
  67729. * @returns The loaded plugin
  67730. */
  67731. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67732. if (sceneFilename === void 0) { sceneFilename = ""; }
  67733. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67734. if (onSuccess === void 0) { onSuccess = null; }
  67735. if (onProgress === void 0) { onProgress = null; }
  67736. if (onError === void 0) { onError = null; }
  67737. if (pluginExtension === void 0) { pluginExtension = null; }
  67738. if (!scene) {
  67739. BABYLON.Tools.Error("No scene available to append to");
  67740. return null;
  67741. }
  67742. if (!sceneFilename) {
  67743. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67744. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67745. }
  67746. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67747. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67748. return null;
  67749. }
  67750. if (SceneLoader.ShowLoadingScreen) {
  67751. scene.getEngine().displayLoadingUI();
  67752. }
  67753. var loadingToken = {};
  67754. scene._addPendingData(loadingToken);
  67755. var disposeHandler = function () {
  67756. scene._removePendingData(loadingToken);
  67757. scene.getEngine().hideLoadingUI();
  67758. };
  67759. var errorHandler = function (message, exception) {
  67760. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67761. if (onError) {
  67762. onError(scene, errorMessage, exception);
  67763. }
  67764. else {
  67765. BABYLON.Tools.Error(errorMessage);
  67766. // should the exception be thrown?
  67767. }
  67768. disposeHandler();
  67769. };
  67770. var progressHandler = onProgress ? function (event) {
  67771. try {
  67772. onProgress(event);
  67773. }
  67774. catch (e) {
  67775. errorHandler("Error in onProgress callback", e);
  67776. }
  67777. } : undefined;
  67778. var successHandler = function () {
  67779. if (onSuccess) {
  67780. try {
  67781. onSuccess(scene);
  67782. }
  67783. catch (e) {
  67784. errorHandler("Error in onSuccess callback", e);
  67785. }
  67786. }
  67787. scene._removePendingData(loadingToken);
  67788. };
  67789. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67790. if (sceneFilename === "") {
  67791. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67792. }
  67793. if (plugin.load) {
  67794. var syncedPlugin = plugin;
  67795. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67796. return;
  67797. }
  67798. scene.loadingPluginName = plugin.name;
  67799. successHandler();
  67800. }
  67801. else {
  67802. var asyncedPlugin = plugin;
  67803. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67804. scene.loadingPluginName = plugin.name;
  67805. successHandler();
  67806. }).catch(function (error) {
  67807. errorHandler(error.message, error);
  67808. });
  67809. }
  67810. if (SceneLoader.ShowLoadingScreen) {
  67811. scene.executeWhenReady(function () {
  67812. scene.getEngine().hideLoadingUI();
  67813. });
  67814. }
  67815. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67816. };
  67817. /**
  67818. * Append a scene
  67819. * @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)
  67820. * @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)
  67821. * @param scene is the instance of BABYLON.Scene to append to
  67822. * @param onProgress a callback with a progress event for each file being loaded
  67823. * @param pluginExtension the extension used to determine the plugin
  67824. * @returns The given scene
  67825. */
  67826. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67827. if (sceneFilename === void 0) { sceneFilename = ""; }
  67828. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67829. if (onProgress === void 0) { onProgress = null; }
  67830. if (pluginExtension === void 0) { pluginExtension = null; }
  67831. return new Promise(function (resolve, reject) {
  67832. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67833. resolve(scene);
  67834. }, onProgress, function (scene, message, exception) {
  67835. reject(exception || new Error(message));
  67836. }, pluginExtension);
  67837. });
  67838. };
  67839. /**
  67840. * Load a scene into an asset container
  67841. * @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)
  67842. * @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)
  67843. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67844. * @param onSuccess a callback with the scene when import succeeds
  67845. * @param onProgress a callback with a progress event for each file being loaded
  67846. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67847. * @param pluginExtension the extension used to determine the plugin
  67848. * @returns The loaded plugin
  67849. */
  67850. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67851. if (sceneFilename === void 0) { sceneFilename = ""; }
  67852. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67853. if (onSuccess === void 0) { onSuccess = null; }
  67854. if (onProgress === void 0) { onProgress = null; }
  67855. if (onError === void 0) { onError = null; }
  67856. if (pluginExtension === void 0) { pluginExtension = null; }
  67857. if (!scene) {
  67858. BABYLON.Tools.Error("No scene available to load asset container to");
  67859. return null;
  67860. }
  67861. if (!sceneFilename) {
  67862. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67863. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67864. }
  67865. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67866. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67867. return null;
  67868. }
  67869. var loadingToken = {};
  67870. scene._addPendingData(loadingToken);
  67871. var disposeHandler = function () {
  67872. scene._removePendingData(loadingToken);
  67873. };
  67874. var errorHandler = function (message, exception) {
  67875. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67876. if (onError) {
  67877. onError(scene, errorMessage, exception);
  67878. }
  67879. else {
  67880. BABYLON.Tools.Error(errorMessage);
  67881. // should the exception be thrown?
  67882. }
  67883. disposeHandler();
  67884. };
  67885. var progressHandler = onProgress ? function (event) {
  67886. try {
  67887. onProgress(event);
  67888. }
  67889. catch (e) {
  67890. errorHandler("Error in onProgress callback", e);
  67891. }
  67892. } : undefined;
  67893. var successHandler = function (assets) {
  67894. if (onSuccess) {
  67895. try {
  67896. onSuccess(assets);
  67897. }
  67898. catch (e) {
  67899. errorHandler("Error in onSuccess callback", e);
  67900. }
  67901. }
  67902. scene._removePendingData(loadingToken);
  67903. };
  67904. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67905. if (plugin.loadAssetContainer) {
  67906. var syncedPlugin = plugin;
  67907. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67908. if (!assetContainer) {
  67909. return;
  67910. }
  67911. scene.loadingPluginName = plugin.name;
  67912. successHandler(assetContainer);
  67913. }
  67914. else if (plugin.loadAssetContainerAsync) {
  67915. var asyncedPlugin = plugin;
  67916. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67917. scene.loadingPluginName = plugin.name;
  67918. successHandler(assetContainer);
  67919. }).catch(function (error) {
  67920. errorHandler(error.message, error);
  67921. });
  67922. }
  67923. else {
  67924. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67925. }
  67926. if (SceneLoader.ShowLoadingScreen) {
  67927. scene.executeWhenReady(function () {
  67928. scene.getEngine().hideLoadingUI();
  67929. });
  67930. }
  67931. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67932. };
  67933. /**
  67934. * Load a scene into an asset container
  67935. * @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)
  67936. * @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)
  67937. * @param scene is the instance of BABYLON.Scene to append to
  67938. * @param onProgress a callback with a progress event for each file being loaded
  67939. * @param pluginExtension the extension used to determine the plugin
  67940. * @returns The loaded asset container
  67941. */
  67942. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67943. if (sceneFilename === void 0) { sceneFilename = ""; }
  67944. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67945. if (onProgress === void 0) { onProgress = null; }
  67946. if (pluginExtension === void 0) { pluginExtension = null; }
  67947. return new Promise(function (resolve, reject) {
  67948. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67949. resolve(assetContainer);
  67950. }, onProgress, function (scene, message, exception) {
  67951. reject(exception || new Error(message));
  67952. }, pluginExtension);
  67953. });
  67954. };
  67955. // Flags
  67956. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67957. SceneLoader._ShowLoadingScreen = true;
  67958. SceneLoader._CleanBoneMatrixWeights = false;
  67959. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67960. // Members
  67961. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67962. SceneLoader._registeredPlugins = {};
  67963. return SceneLoader;
  67964. }());
  67965. BABYLON.SceneLoader = SceneLoader;
  67966. ;
  67967. })(BABYLON || (BABYLON = {}));
  67968. //# sourceMappingURL=babylon.sceneLoader.js.map
  67969. var BABYLON;
  67970. (function (BABYLON) {
  67971. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67972. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67973. var parsedMaterial = parsedData.materials[index];
  67974. if (parsedMaterial.id === id) {
  67975. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67976. }
  67977. }
  67978. return null;
  67979. };
  67980. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67981. for (var i in names) {
  67982. if (mesh.name === names[i]) {
  67983. hierarchyIds.push(mesh.id);
  67984. return true;
  67985. }
  67986. }
  67987. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67988. hierarchyIds.push(mesh.id);
  67989. return true;
  67990. }
  67991. return false;
  67992. };
  67993. var logOperation = function (operation, producer) {
  67994. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67995. };
  67996. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67997. if (addToScene === void 0) { addToScene = false; }
  67998. var container = new BABYLON.AssetContainer(scene);
  67999. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68000. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68001. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68002. // and avoid problems with multiple concurrent .babylon loads.
  68003. var log = "importScene has failed JSON parse";
  68004. try {
  68005. var parsedData = JSON.parse(data);
  68006. log = "";
  68007. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68008. var index;
  68009. var cache;
  68010. // Lights
  68011. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68012. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68013. var parsedLight = parsedData.lights[index];
  68014. var light = BABYLON.Light.Parse(parsedLight, scene);
  68015. if (light) {
  68016. container.lights.push(light);
  68017. log += (index === 0 ? "\n\tLights:" : "");
  68018. log += "\n\t\t" + light.toString(fullDetails);
  68019. }
  68020. }
  68021. }
  68022. // Animations
  68023. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68024. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68025. var parsedAnimation = parsedData.animations[index];
  68026. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68027. scene.animations.push(animation);
  68028. container.animations.push(animation);
  68029. log += (index === 0 ? "\n\tAnimations:" : "");
  68030. log += "\n\t\t" + animation.toString(fullDetails);
  68031. }
  68032. }
  68033. // Materials
  68034. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68035. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68036. var parsedMaterial = parsedData.materials[index];
  68037. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68038. container.materials.push(mat);
  68039. log += (index === 0 ? "\n\tMaterials:" : "");
  68040. log += "\n\t\t" + mat.toString(fullDetails);
  68041. }
  68042. }
  68043. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68044. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68045. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68046. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68047. container.multiMaterials.push(mmat);
  68048. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68049. log += "\n\t\t" + mmat.toString(fullDetails);
  68050. }
  68051. }
  68052. // Morph targets
  68053. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68054. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68055. var managerData = _a[_i];
  68056. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68057. }
  68058. }
  68059. // Skeletons
  68060. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68061. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68062. var parsedSkeleton = parsedData.skeletons[index];
  68063. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68064. container.skeletons.push(skeleton);
  68065. log += (index === 0 ? "\n\tSkeletons:" : "");
  68066. log += "\n\t\t" + skeleton.toString(fullDetails);
  68067. }
  68068. }
  68069. // Geometries
  68070. var geometries = parsedData.geometries;
  68071. if (geometries !== undefined && geometries !== null) {
  68072. var addedGeometry = new Array();
  68073. // Boxes
  68074. var boxes = geometries.boxes;
  68075. if (boxes !== undefined && boxes !== null) {
  68076. for (index = 0, cache = boxes.length; index < cache; index++) {
  68077. var parsedBox = boxes[index];
  68078. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68079. }
  68080. }
  68081. // Spheres
  68082. var spheres = geometries.spheres;
  68083. if (spheres !== undefined && spheres !== null) {
  68084. for (index = 0, cache = spheres.length; index < cache; index++) {
  68085. var parsedSphere = spheres[index];
  68086. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68087. }
  68088. }
  68089. // Cylinders
  68090. var cylinders = geometries.cylinders;
  68091. if (cylinders !== undefined && cylinders !== null) {
  68092. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68093. var parsedCylinder = cylinders[index];
  68094. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68095. }
  68096. }
  68097. // Toruses
  68098. var toruses = geometries.toruses;
  68099. if (toruses !== undefined && toruses !== null) {
  68100. for (index = 0, cache = toruses.length; index < cache; index++) {
  68101. var parsedTorus = toruses[index];
  68102. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68103. }
  68104. }
  68105. // Grounds
  68106. var grounds = geometries.grounds;
  68107. if (grounds !== undefined && grounds !== null) {
  68108. for (index = 0, cache = grounds.length; index < cache; index++) {
  68109. var parsedGround = grounds[index];
  68110. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68111. }
  68112. }
  68113. // Planes
  68114. var planes = geometries.planes;
  68115. if (planes !== undefined && planes !== null) {
  68116. for (index = 0, cache = planes.length; index < cache; index++) {
  68117. var parsedPlane = planes[index];
  68118. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68119. }
  68120. }
  68121. // TorusKnots
  68122. var torusKnots = geometries.torusKnots;
  68123. if (torusKnots !== undefined && torusKnots !== null) {
  68124. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68125. var parsedTorusKnot = torusKnots[index];
  68126. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68127. }
  68128. }
  68129. // VertexData
  68130. var vertexData = geometries.vertexData;
  68131. if (vertexData !== undefined && vertexData !== null) {
  68132. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68133. var parsedVertexData = vertexData[index];
  68134. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68135. }
  68136. }
  68137. addedGeometry.forEach(function (g) {
  68138. if (g) {
  68139. container.geometries.push(g);
  68140. }
  68141. });
  68142. }
  68143. // Transform nodes
  68144. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68145. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68146. var parsedTransformNode = parsedData.transformNodes[index];
  68147. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68148. container.transformNodes.push(node);
  68149. }
  68150. }
  68151. // Meshes
  68152. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68153. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68154. var parsedMesh = parsedData.meshes[index];
  68155. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68156. container.meshes.push(mesh);
  68157. log += (index === 0 ? "\n\tMeshes:" : "");
  68158. log += "\n\t\t" + mesh.toString(fullDetails);
  68159. }
  68160. }
  68161. // Cameras
  68162. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68163. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68164. var parsedCamera = parsedData.cameras[index];
  68165. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68166. container.cameras.push(camera);
  68167. log += (index === 0 ? "\n\tCameras:" : "");
  68168. log += "\n\t\t" + camera.toString(fullDetails);
  68169. }
  68170. }
  68171. // Browsing all the graph to connect the dots
  68172. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68173. var camera = scene.cameras[index];
  68174. if (camera._waitingParentId) {
  68175. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68176. camera._waitingParentId = null;
  68177. }
  68178. }
  68179. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68180. var light_1 = scene.lights[index];
  68181. if (light_1 && light_1._waitingParentId) {
  68182. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68183. light_1._waitingParentId = null;
  68184. }
  68185. }
  68186. // Sounds
  68187. // TODO: add sound
  68188. var loadedSounds = [];
  68189. var loadedSound;
  68190. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68191. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68192. var parsedSound = parsedData.sounds[index];
  68193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68194. if (!parsedSound.url)
  68195. parsedSound.url = parsedSound.name;
  68196. if (!loadedSounds[parsedSound.url]) {
  68197. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68198. loadedSounds[parsedSound.url] = loadedSound;
  68199. container.sounds.push(loadedSound);
  68200. }
  68201. else {
  68202. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68203. }
  68204. }
  68205. else {
  68206. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68207. }
  68208. }
  68209. }
  68210. loadedSounds = [];
  68211. // Connect parents & children and parse actions
  68212. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68213. var transformNode = scene.transformNodes[index];
  68214. if (transformNode._waitingParentId) {
  68215. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68216. transformNode._waitingParentId = null;
  68217. }
  68218. }
  68219. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68220. var mesh = scene.meshes[index];
  68221. if (mesh._waitingParentId) {
  68222. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68223. mesh._waitingParentId = null;
  68224. }
  68225. if (mesh._waitingActions) {
  68226. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68227. mesh._waitingActions = null;
  68228. }
  68229. }
  68230. // freeze world matrix application
  68231. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68232. var currentMesh = scene.meshes[index];
  68233. if (currentMesh._waitingFreezeWorldMatrix) {
  68234. currentMesh.freezeWorldMatrix();
  68235. currentMesh._waitingFreezeWorldMatrix = null;
  68236. }
  68237. else {
  68238. currentMesh.computeWorldMatrix(true);
  68239. }
  68240. }
  68241. // Shadows
  68242. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68243. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68244. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68245. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68246. // SG would be available on their associated lights
  68247. }
  68248. }
  68249. // Lights exclusions / inclusions
  68250. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68251. var light_2 = scene.lights[index];
  68252. // Excluded check
  68253. if (light_2._excludedMeshesIds.length > 0) {
  68254. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68255. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68256. if (excludedMesh) {
  68257. light_2.excludedMeshes.push(excludedMesh);
  68258. }
  68259. }
  68260. light_2._excludedMeshesIds = [];
  68261. }
  68262. // Included check
  68263. if (light_2._includedOnlyMeshesIds.length > 0) {
  68264. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68265. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68266. if (includedOnlyMesh) {
  68267. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68268. }
  68269. }
  68270. light_2._includedOnlyMeshesIds = [];
  68271. }
  68272. }
  68273. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68274. // Actions (scene)
  68275. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68276. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68277. }
  68278. if (!addToScene) {
  68279. container.removeAllFromScene();
  68280. }
  68281. }
  68282. catch (err) {
  68283. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68284. if (onError) {
  68285. onError(msg, err);
  68286. }
  68287. else {
  68288. BABYLON.Tools.Log(msg);
  68289. throw err;
  68290. }
  68291. }
  68292. finally {
  68293. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68294. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68295. }
  68296. }
  68297. return container;
  68298. };
  68299. BABYLON.SceneLoader.RegisterPlugin({
  68300. name: "babylon.js",
  68301. extensions: ".babylon",
  68302. canDirectLoad: function (data) {
  68303. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68304. return true;
  68305. }
  68306. return false;
  68307. },
  68308. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68309. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68310. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68311. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68312. // and avoid problems with multiple concurrent .babylon loads.
  68313. var log = "importMesh has failed JSON parse";
  68314. try {
  68315. var parsedData = JSON.parse(data);
  68316. log = "";
  68317. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68318. if (!meshesNames) {
  68319. meshesNames = null;
  68320. }
  68321. else if (!Array.isArray(meshesNames)) {
  68322. meshesNames = [meshesNames];
  68323. }
  68324. var hierarchyIds = new Array();
  68325. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68326. var loadedSkeletonsIds = [];
  68327. var loadedMaterialsIds = [];
  68328. var index;
  68329. var cache;
  68330. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68331. var parsedMesh = parsedData.meshes[index];
  68332. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68333. if (meshesNames !== null) {
  68334. // Remove found mesh name from list.
  68335. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68336. }
  68337. //Geometry?
  68338. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68339. //does the file contain geometries?
  68340. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68341. //find the correct geometry and add it to the scene
  68342. var found = false;
  68343. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68344. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68345. return;
  68346. }
  68347. else {
  68348. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68349. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68350. switch (geometryType) {
  68351. case "boxes":
  68352. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68353. break;
  68354. case "spheres":
  68355. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68356. break;
  68357. case "cylinders":
  68358. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68359. break;
  68360. case "toruses":
  68361. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68362. break;
  68363. case "grounds":
  68364. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68365. break;
  68366. case "planes":
  68367. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68368. break;
  68369. case "torusKnots":
  68370. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68371. break;
  68372. case "vertexData":
  68373. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68374. break;
  68375. }
  68376. found = true;
  68377. }
  68378. });
  68379. }
  68380. });
  68381. if (found === false) {
  68382. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68383. }
  68384. }
  68385. }
  68386. // Material ?
  68387. if (parsedMesh.materialId) {
  68388. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68389. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68390. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68391. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68392. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68393. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68394. var subMatId = parsedMultiMaterial.materials[matIndex];
  68395. loadedMaterialsIds.push(subMatId);
  68396. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68397. if (mat) {
  68398. log += "\n\tMaterial " + mat.toString(fullDetails);
  68399. }
  68400. }
  68401. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68402. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68403. if (mmat) {
  68404. materialFound = true;
  68405. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68406. }
  68407. break;
  68408. }
  68409. }
  68410. }
  68411. if (materialFound === false) {
  68412. loadedMaterialsIds.push(parsedMesh.materialId);
  68413. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68414. if (!mat) {
  68415. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68416. }
  68417. else {
  68418. log += "\n\tMaterial " + mat.toString(fullDetails);
  68419. }
  68420. }
  68421. }
  68422. // Skeleton ?
  68423. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68424. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68425. if (skeletonAlreadyLoaded === false) {
  68426. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68427. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68428. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68429. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68430. skeletons.push(skeleton);
  68431. loadedSkeletonsIds.push(parsedSkeleton.id);
  68432. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68433. }
  68434. }
  68435. }
  68436. }
  68437. // Morph targets ?
  68438. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68439. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68440. var managerData = _a[_i];
  68441. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68442. }
  68443. }
  68444. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68445. meshes.push(mesh);
  68446. log += "\n\tMesh " + mesh.toString(fullDetails);
  68447. }
  68448. }
  68449. // Connecting parents
  68450. var currentMesh;
  68451. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68452. currentMesh = scene.meshes[index];
  68453. if (currentMesh._waitingParentId) {
  68454. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68455. currentMesh._waitingParentId = null;
  68456. }
  68457. }
  68458. // freeze and compute world matrix application
  68459. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68460. currentMesh = scene.meshes[index];
  68461. if (currentMesh._waitingFreezeWorldMatrix) {
  68462. currentMesh.freezeWorldMatrix();
  68463. currentMesh._waitingFreezeWorldMatrix = null;
  68464. }
  68465. else {
  68466. currentMesh.computeWorldMatrix(true);
  68467. }
  68468. }
  68469. }
  68470. // Particles
  68471. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68472. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  68473. if (parser) {
  68474. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68475. var parsedParticleSystem = parsedData.particleSystems[index];
  68476. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68477. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  68478. }
  68479. }
  68480. }
  68481. }
  68482. return true;
  68483. }
  68484. catch (err) {
  68485. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68486. if (onError) {
  68487. onError(msg, err);
  68488. }
  68489. else {
  68490. BABYLON.Tools.Log(msg);
  68491. throw err;
  68492. }
  68493. }
  68494. finally {
  68495. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68496. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68497. }
  68498. }
  68499. return false;
  68500. },
  68501. load: function (scene, data, rootUrl, onError) {
  68502. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68503. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68504. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68505. // and avoid problems with multiple concurrent .babylon loads.
  68506. var log = "importScene has failed JSON parse";
  68507. try {
  68508. var parsedData = JSON.parse(data);
  68509. log = "";
  68510. // Scene
  68511. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68512. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68513. }
  68514. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68515. scene.autoClear = parsedData.autoClear;
  68516. }
  68517. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68518. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68519. }
  68520. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68521. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68522. }
  68523. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68524. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68525. }
  68526. // Fog
  68527. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68528. scene.fogMode = parsedData.fogMode;
  68529. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68530. scene.fogStart = parsedData.fogStart;
  68531. scene.fogEnd = parsedData.fogEnd;
  68532. scene.fogDensity = parsedData.fogDensity;
  68533. log += "\tFog mode for scene: ";
  68534. switch (scene.fogMode) {
  68535. // getters not compiling, so using hardcoded
  68536. case 1:
  68537. log += "exp\n";
  68538. break;
  68539. case 2:
  68540. log += "exp2\n";
  68541. break;
  68542. case 3:
  68543. log += "linear\n";
  68544. break;
  68545. }
  68546. }
  68547. //Physics
  68548. if (parsedData.physicsEnabled) {
  68549. var physicsPlugin;
  68550. if (parsedData.physicsEngine === "cannon") {
  68551. physicsPlugin = new BABYLON.CannonJSPlugin();
  68552. }
  68553. else if (parsedData.physicsEngine === "oimo") {
  68554. physicsPlugin = new BABYLON.OimoJSPlugin();
  68555. }
  68556. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68557. //else - default engine, which is currently oimo
  68558. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68559. scene.enablePhysics(physicsGravity, physicsPlugin);
  68560. }
  68561. // Metadata
  68562. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68563. scene.metadata = parsedData.metadata;
  68564. }
  68565. //collisions, if defined. otherwise, default is true
  68566. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68567. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68568. }
  68569. scene.workerCollisions = !!parsedData.workerCollisions;
  68570. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68571. if (!container) {
  68572. return false;
  68573. }
  68574. if (parsedData.autoAnimate) {
  68575. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68576. }
  68577. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68578. scene.setActiveCameraByID(parsedData.activeCameraID);
  68579. }
  68580. // Environment texture
  68581. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68582. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68583. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68584. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68585. if (parsedData.environmentTextureRotationY) {
  68586. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68587. }
  68588. scene.environmentTexture = hdrTexture;
  68589. }
  68590. else {
  68591. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68592. if (parsedData.environmentTextureRotationY) {
  68593. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68594. }
  68595. scene.environmentTexture = cubeTexture;
  68596. }
  68597. if (parsedData.createDefaultSkybox === true) {
  68598. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68599. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68600. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68601. }
  68602. }
  68603. // Finish
  68604. return true;
  68605. }
  68606. catch (err) {
  68607. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68608. if (onError) {
  68609. onError(msg, err);
  68610. }
  68611. else {
  68612. BABYLON.Tools.Log(msg);
  68613. throw err;
  68614. }
  68615. }
  68616. finally {
  68617. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68618. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68619. }
  68620. }
  68621. return false;
  68622. },
  68623. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68624. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68625. return container;
  68626. }
  68627. });
  68628. })(BABYLON || (BABYLON = {}));
  68629. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68630. var BABYLON;
  68631. (function (BABYLON) {
  68632. var FilesInput = /** @class */ (function () {
  68633. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68634. this.onProcessFileCallback = function () { return true; };
  68635. this._engine = engine;
  68636. this._currentScene = scene;
  68637. this._sceneLoadedCallback = sceneLoadedCallback;
  68638. this._progressCallback = progressCallback;
  68639. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68640. this._textureLoadingCallback = textureLoadingCallback;
  68641. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68642. this._onReloadCallback = onReloadCallback;
  68643. this._errorCallback = errorCallback;
  68644. }
  68645. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68646. var _this = this;
  68647. if (elementToMonitor) {
  68648. this._elementToMonitor = elementToMonitor;
  68649. this._dragEnterHandler = function (e) { _this.drag(e); };
  68650. this._dragOverHandler = function (e) { _this.drag(e); };
  68651. this._dropHandler = function (e) { _this.drop(e); };
  68652. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68653. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68654. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68655. }
  68656. };
  68657. FilesInput.prototype.dispose = function () {
  68658. if (!this._elementToMonitor) {
  68659. return;
  68660. }
  68661. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68662. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68663. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68664. };
  68665. FilesInput.prototype.renderFunction = function () {
  68666. if (this._additionalRenderLoopLogicCallback) {
  68667. this._additionalRenderLoopLogicCallback();
  68668. }
  68669. if (this._currentScene) {
  68670. if (this._textureLoadingCallback) {
  68671. var remaining = this._currentScene.getWaitingItemsCount();
  68672. if (remaining > 0) {
  68673. this._textureLoadingCallback(remaining);
  68674. }
  68675. }
  68676. this._currentScene.render();
  68677. }
  68678. };
  68679. FilesInput.prototype.drag = function (e) {
  68680. e.stopPropagation();
  68681. e.preventDefault();
  68682. };
  68683. FilesInput.prototype.drop = function (eventDrop) {
  68684. eventDrop.stopPropagation();
  68685. eventDrop.preventDefault();
  68686. this.loadFiles(eventDrop);
  68687. };
  68688. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68689. var _this = this;
  68690. var reader = folder.createReader();
  68691. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68692. reader.readEntries(function (entries) {
  68693. remaining.count += entries.length;
  68694. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68695. var entry = entries_1[_i];
  68696. if (entry.isFile) {
  68697. entry.file(function (file) {
  68698. file.correctName = relativePath + file.name;
  68699. files.push(file);
  68700. if (--remaining.count === 0) {
  68701. callback();
  68702. }
  68703. });
  68704. }
  68705. else if (entry.isDirectory) {
  68706. _this._traverseFolder(entry, files, remaining, callback);
  68707. }
  68708. }
  68709. if (--remaining.count) {
  68710. callback();
  68711. }
  68712. });
  68713. };
  68714. FilesInput.prototype._processFiles = function (files) {
  68715. for (var i = 0; i < files.length; i++) {
  68716. var name = files[i].correctName.toLowerCase();
  68717. var extension = name.split('.').pop();
  68718. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68719. continue;
  68720. }
  68721. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68722. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68723. this._sceneFileToLoad = files[i];
  68724. }
  68725. else {
  68726. FilesInput.FilesToLoad[name] = files[i];
  68727. }
  68728. }
  68729. };
  68730. FilesInput.prototype.loadFiles = function (event) {
  68731. var _this = this;
  68732. if (this._startingProcessingFilesCallback)
  68733. this._startingProcessingFilesCallback();
  68734. // Handling data transfer via drag'n'drop
  68735. if (event && event.dataTransfer && event.dataTransfer.files) {
  68736. this._filesToLoad = event.dataTransfer.files;
  68737. }
  68738. // Handling files from input files
  68739. if (event && event.target && event.target.files) {
  68740. this._filesToLoad = event.target.files;
  68741. }
  68742. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68743. var files_1 = new Array();
  68744. var folders = [];
  68745. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68746. for (var i = 0; i < this._filesToLoad.length; i++) {
  68747. var fileToLoad = this._filesToLoad[i];
  68748. var name_1 = fileToLoad.name.toLowerCase();
  68749. var entry = void 0;
  68750. fileToLoad.correctName = name_1;
  68751. if (items) {
  68752. var item = items[i];
  68753. if (item.getAsEntry) {
  68754. entry = item.getAsEntry();
  68755. }
  68756. else if (item.webkitGetAsEntry) {
  68757. entry = item.webkitGetAsEntry();
  68758. }
  68759. }
  68760. if (!entry) {
  68761. files_1.push(fileToLoad);
  68762. }
  68763. else {
  68764. if (entry.isDirectory) {
  68765. folders.push(entry);
  68766. }
  68767. else {
  68768. files_1.push(fileToLoad);
  68769. }
  68770. }
  68771. }
  68772. if (folders.length === 0) {
  68773. this._processFiles(files_1);
  68774. this._processReload();
  68775. }
  68776. else {
  68777. var remaining = { count: folders.length };
  68778. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68779. var folder = folders_1[_i];
  68780. this._traverseFolder(folder, files_1, remaining, function () {
  68781. _this._processFiles(files_1);
  68782. if (remaining.count === 0) {
  68783. _this._processReload();
  68784. }
  68785. });
  68786. }
  68787. }
  68788. }
  68789. };
  68790. FilesInput.prototype._processReload = function () {
  68791. if (this._onReloadCallback) {
  68792. this._onReloadCallback(this._sceneFileToLoad);
  68793. }
  68794. else {
  68795. this.reload();
  68796. }
  68797. };
  68798. FilesInput.prototype.reload = function () {
  68799. var _this = this;
  68800. // If a scene file has been provided
  68801. if (this._sceneFileToLoad) {
  68802. if (this._currentScene) {
  68803. if (BABYLON.Tools.errorsCount > 0) {
  68804. BABYLON.Tools.ClearLogCache();
  68805. }
  68806. this._engine.stopRenderLoop();
  68807. }
  68808. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68809. if (_this._progressCallback) {
  68810. _this._progressCallback(progress);
  68811. }
  68812. }).then(function (scene) {
  68813. if (_this._currentScene) {
  68814. _this._currentScene.dispose();
  68815. }
  68816. _this._currentScene = scene;
  68817. if (_this._sceneLoadedCallback) {
  68818. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68819. }
  68820. // Wait for textures and shaders to be ready
  68821. _this._currentScene.executeWhenReady(function () {
  68822. _this._engine.runRenderLoop(function () {
  68823. _this.renderFunction();
  68824. });
  68825. });
  68826. }).catch(function (error) {
  68827. if (_this._errorCallback) {
  68828. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68829. }
  68830. });
  68831. }
  68832. else {
  68833. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68834. }
  68835. };
  68836. FilesInput.FilesToLoad = {};
  68837. return FilesInput;
  68838. }());
  68839. BABYLON.FilesInput = FilesInput;
  68840. })(BABYLON || (BABYLON = {}));
  68841. //# sourceMappingURL=babylon.filesInput.js.map
  68842. var BABYLON;
  68843. (function (BABYLON) {
  68844. /**
  68845. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68846. * The underlying implementation relies on an associative array to ensure the best performances.
  68847. * The value can be anything including 'null' but except 'undefined'
  68848. */
  68849. var StringDictionary = /** @class */ (function () {
  68850. function StringDictionary() {
  68851. this._count = 0;
  68852. this._data = {};
  68853. }
  68854. /**
  68855. * This will clear this dictionary and copy the content from the 'source' one.
  68856. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68857. * @param source the dictionary to take the content from and copy to this dictionary
  68858. */
  68859. StringDictionary.prototype.copyFrom = function (source) {
  68860. var _this = this;
  68861. this.clear();
  68862. source.forEach(function (t, v) { return _this.add(t, v); });
  68863. };
  68864. /**
  68865. * Get a value based from its key
  68866. * @param key the given key to get the matching value from
  68867. * @return the value if found, otherwise undefined is returned
  68868. */
  68869. StringDictionary.prototype.get = function (key) {
  68870. var val = this._data[key];
  68871. if (val !== undefined) {
  68872. return val;
  68873. }
  68874. return undefined;
  68875. };
  68876. /**
  68877. * Get a value from its key or add it if it doesn't exist.
  68878. * This method will ensure you that a given key/data will be present in the dictionary.
  68879. * @param key the given key to get the matching value from
  68880. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68881. * The factory will only be invoked if there's no data for the given key.
  68882. * @return the value corresponding to the key.
  68883. */
  68884. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68885. var val = this.get(key);
  68886. if (val !== undefined) {
  68887. return val;
  68888. }
  68889. val = factory(key);
  68890. if (val) {
  68891. this.add(key, val);
  68892. }
  68893. return val;
  68894. };
  68895. /**
  68896. * Get a value from its key if present in the dictionary otherwise add it
  68897. * @param key the key to get the value from
  68898. * @param val if there's no such key/value pair in the dictionary add it with this value
  68899. * @return the value corresponding to the key
  68900. */
  68901. StringDictionary.prototype.getOrAdd = function (key, val) {
  68902. var curVal = this.get(key);
  68903. if (curVal !== undefined) {
  68904. return curVal;
  68905. }
  68906. this.add(key, val);
  68907. return val;
  68908. };
  68909. /**
  68910. * Check if there's a given key in the dictionary
  68911. * @param key the key to check for
  68912. * @return true if the key is present, false otherwise
  68913. */
  68914. StringDictionary.prototype.contains = function (key) {
  68915. return this._data[key] !== undefined;
  68916. };
  68917. /**
  68918. * Add a new key and its corresponding value
  68919. * @param key the key to add
  68920. * @param value the value corresponding to the key
  68921. * @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
  68922. */
  68923. StringDictionary.prototype.add = function (key, value) {
  68924. if (this._data[key] !== undefined) {
  68925. return false;
  68926. }
  68927. this._data[key] = value;
  68928. ++this._count;
  68929. return true;
  68930. };
  68931. StringDictionary.prototype.set = function (key, value) {
  68932. if (this._data[key] === undefined) {
  68933. return false;
  68934. }
  68935. this._data[key] = value;
  68936. return true;
  68937. };
  68938. /**
  68939. * Get the element of the given key and remove it from the dictionary
  68940. * @param key
  68941. */
  68942. StringDictionary.prototype.getAndRemove = function (key) {
  68943. var val = this.get(key);
  68944. if (val !== undefined) {
  68945. delete this._data[key];
  68946. --this._count;
  68947. return val;
  68948. }
  68949. return null;
  68950. };
  68951. /**
  68952. * Remove a key/value from the dictionary.
  68953. * @param key the key to remove
  68954. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68955. */
  68956. StringDictionary.prototype.remove = function (key) {
  68957. if (this.contains(key)) {
  68958. delete this._data[key];
  68959. --this._count;
  68960. return true;
  68961. }
  68962. return false;
  68963. };
  68964. /**
  68965. * Clear the whole content of the dictionary
  68966. */
  68967. StringDictionary.prototype.clear = function () {
  68968. this._data = {};
  68969. this._count = 0;
  68970. };
  68971. Object.defineProperty(StringDictionary.prototype, "count", {
  68972. get: function () {
  68973. return this._count;
  68974. },
  68975. enumerable: true,
  68976. configurable: true
  68977. });
  68978. /**
  68979. * Execute a callback on each key/val of the dictionary.
  68980. * Note that you can remove any element in this dictionary in the callback implementation
  68981. * @param callback the callback to execute on a given key/value pair
  68982. */
  68983. StringDictionary.prototype.forEach = function (callback) {
  68984. for (var cur in this._data) {
  68985. var val = this._data[cur];
  68986. callback(cur, val);
  68987. }
  68988. };
  68989. /**
  68990. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68991. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68992. * Note that you can remove any element in this dictionary in the callback implementation
  68993. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68994. */
  68995. StringDictionary.prototype.first = function (callback) {
  68996. for (var cur in this._data) {
  68997. var val = this._data[cur];
  68998. var res = callback(cur, val);
  68999. if (res) {
  69000. return res;
  69001. }
  69002. }
  69003. return null;
  69004. };
  69005. return StringDictionary;
  69006. }());
  69007. BABYLON.StringDictionary = StringDictionary;
  69008. })(BABYLON || (BABYLON = {}));
  69009. //# sourceMappingURL=babylon.stringDictionary.js.map
  69010. var BABYLON;
  69011. (function (BABYLON) {
  69012. var Tags = /** @class */ (function () {
  69013. function Tags() {
  69014. }
  69015. Tags.EnableFor = function (obj) {
  69016. obj._tags = obj._tags || {};
  69017. obj.hasTags = function () {
  69018. return Tags.HasTags(obj);
  69019. };
  69020. obj.addTags = function (tagsString) {
  69021. return Tags.AddTagsTo(obj, tagsString);
  69022. };
  69023. obj.removeTags = function (tagsString) {
  69024. return Tags.RemoveTagsFrom(obj, tagsString);
  69025. };
  69026. obj.matchesTagsQuery = function (tagsQuery) {
  69027. return Tags.MatchesQuery(obj, tagsQuery);
  69028. };
  69029. };
  69030. Tags.DisableFor = function (obj) {
  69031. delete obj._tags;
  69032. delete obj.hasTags;
  69033. delete obj.addTags;
  69034. delete obj.removeTags;
  69035. delete obj.matchesTagsQuery;
  69036. };
  69037. Tags.HasTags = function (obj) {
  69038. if (!obj._tags) {
  69039. return false;
  69040. }
  69041. return !BABYLON.Tools.IsEmpty(obj._tags);
  69042. };
  69043. Tags.GetTags = function (obj, asString) {
  69044. if (asString === void 0) { asString = true; }
  69045. if (!obj._tags) {
  69046. return null;
  69047. }
  69048. if (asString) {
  69049. var tagsArray = [];
  69050. for (var tag in obj._tags) {
  69051. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69052. tagsArray.push(tag);
  69053. }
  69054. }
  69055. return tagsArray.join(" ");
  69056. }
  69057. else {
  69058. return obj._tags;
  69059. }
  69060. };
  69061. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69062. // a tag cannot start with '||', '&&', and '!'
  69063. // it cannot contain whitespaces
  69064. Tags.AddTagsTo = function (obj, tagsString) {
  69065. if (!tagsString) {
  69066. return;
  69067. }
  69068. if (typeof tagsString !== "string") {
  69069. return;
  69070. }
  69071. var tags = tagsString.split(" ");
  69072. tags.forEach(function (tag, index, array) {
  69073. Tags._AddTagTo(obj, tag);
  69074. });
  69075. };
  69076. Tags._AddTagTo = function (obj, tag) {
  69077. tag = tag.trim();
  69078. if (tag === "" || tag === "true" || tag === "false") {
  69079. return;
  69080. }
  69081. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69082. return;
  69083. }
  69084. Tags.EnableFor(obj);
  69085. obj._tags[tag] = true;
  69086. };
  69087. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69088. if (!Tags.HasTags(obj)) {
  69089. return;
  69090. }
  69091. var tags = tagsString.split(" ");
  69092. for (var t in tags) {
  69093. Tags._RemoveTagFrom(obj, tags[t]);
  69094. }
  69095. };
  69096. Tags._RemoveTagFrom = function (obj, tag) {
  69097. delete obj._tags[tag];
  69098. };
  69099. Tags.MatchesQuery = function (obj, tagsQuery) {
  69100. if (tagsQuery === undefined) {
  69101. return true;
  69102. }
  69103. if (tagsQuery === "") {
  69104. return Tags.HasTags(obj);
  69105. }
  69106. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69107. };
  69108. return Tags;
  69109. }());
  69110. BABYLON.Tags = Tags;
  69111. })(BABYLON || (BABYLON = {}));
  69112. //# sourceMappingURL=babylon.tags.js.map
  69113. var BABYLON;
  69114. (function (BABYLON) {
  69115. /**
  69116. * Class used to evalaute queries containing `and` and `or` operators
  69117. */
  69118. var AndOrNotEvaluator = /** @class */ (function () {
  69119. function AndOrNotEvaluator() {
  69120. }
  69121. /**
  69122. * Evaluate a query
  69123. * @param query defines the query to evaluate
  69124. * @param evaluateCallback defines the callback used to filter result
  69125. * @returns true if the query matches
  69126. */
  69127. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69128. if (!query.match(/\([^\(\)]*\)/g)) {
  69129. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69130. }
  69131. else {
  69132. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69133. // remove parenthesis
  69134. r = r.slice(1, r.length - 1);
  69135. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69136. });
  69137. }
  69138. if (query === "true") {
  69139. return true;
  69140. }
  69141. if (query === "false") {
  69142. return false;
  69143. }
  69144. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69145. };
  69146. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69147. evaluateCallback = evaluateCallback || (function (r) {
  69148. return r === "true" ? true : false;
  69149. });
  69150. var result;
  69151. var or = parenthesisContent.split("||");
  69152. for (var i in or) {
  69153. if (or.hasOwnProperty(i)) {
  69154. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69155. var and = ori.split("&&");
  69156. if (and.length > 1) {
  69157. for (var j = 0; j < and.length; ++j) {
  69158. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69159. if (andj !== "true" && andj !== "false") {
  69160. if (andj[0] === "!") {
  69161. result = !evaluateCallback(andj.substring(1));
  69162. }
  69163. else {
  69164. result = evaluateCallback(andj);
  69165. }
  69166. }
  69167. else {
  69168. result = andj === "true" ? true : false;
  69169. }
  69170. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69171. ori = "false";
  69172. break;
  69173. }
  69174. }
  69175. }
  69176. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69177. result = true;
  69178. break;
  69179. }
  69180. // result equals false (or undefined)
  69181. if (ori !== "true" && ori !== "false") {
  69182. if (ori[0] === "!") {
  69183. result = !evaluateCallback(ori.substring(1));
  69184. }
  69185. else {
  69186. result = evaluateCallback(ori);
  69187. }
  69188. }
  69189. else {
  69190. result = ori === "true" ? true : false;
  69191. }
  69192. }
  69193. }
  69194. // the whole parenthesis scope is replaced by 'true' or 'false'
  69195. return result ? "true" : "false";
  69196. };
  69197. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69198. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69199. // remove whitespaces
  69200. r = r.replace(/[\s]/g, function () { return ""; });
  69201. return r.length % 2 ? "!" : "";
  69202. });
  69203. booleanString = booleanString.trim();
  69204. if (booleanString === "!true") {
  69205. booleanString = "false";
  69206. }
  69207. else if (booleanString === "!false") {
  69208. booleanString = "true";
  69209. }
  69210. return booleanString;
  69211. };
  69212. return AndOrNotEvaluator;
  69213. }());
  69214. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69215. })(BABYLON || (BABYLON = {}));
  69216. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69217. var BABYLON;
  69218. (function (BABYLON) {
  69219. /**
  69220. * Class used to enable access to IndexedDB
  69221. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69222. */
  69223. var Database = /** @class */ (function () {
  69224. /**
  69225. * Creates a new Database
  69226. * @param urlToScene defines the url to load the scene
  69227. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69228. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69229. */
  69230. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69231. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69232. var _this = this;
  69233. // Handling various flavors of prefixed version of IndexedDB
  69234. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69235. this.callbackManifestChecked = callbackManifestChecked;
  69236. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69237. this.db = null;
  69238. this._enableSceneOffline = false;
  69239. this._enableTexturesOffline = false;
  69240. this.manifestVersionFound = 0;
  69241. this.mustUpdateRessources = false;
  69242. this.hasReachedQuota = false;
  69243. if (!Database.IDBStorageEnabled) {
  69244. this.callbackManifestChecked(true);
  69245. }
  69246. else {
  69247. if (disableManifestCheck) {
  69248. this._enableSceneOffline = true;
  69249. this._enableTexturesOffline = true;
  69250. this.manifestVersionFound = 1;
  69251. BABYLON.Tools.SetImmediate(function () {
  69252. _this.callbackManifestChecked(true);
  69253. });
  69254. }
  69255. else {
  69256. this._checkManifestFile();
  69257. }
  69258. }
  69259. }
  69260. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69261. /**
  69262. * Gets a boolean indicating if scene must be saved in the database
  69263. */
  69264. get: function () {
  69265. return this._enableSceneOffline;
  69266. },
  69267. enumerable: true,
  69268. configurable: true
  69269. });
  69270. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69271. /**
  69272. * Gets a boolean indicating if textures must be saved in the database
  69273. */
  69274. get: function () {
  69275. return this._enableTexturesOffline;
  69276. },
  69277. enumerable: true,
  69278. configurable: true
  69279. });
  69280. Database.prototype._checkManifestFile = function () {
  69281. var _this = this;
  69282. var noManifestFile = function () {
  69283. _this._enableSceneOffline = false;
  69284. _this._enableTexturesOffline = false;
  69285. _this.callbackManifestChecked(false);
  69286. };
  69287. var timeStampUsed = false;
  69288. var manifestURL = this.currentSceneUrl + ".manifest";
  69289. var xhr = new XMLHttpRequest();
  69290. if (navigator.onLine) {
  69291. // Adding a timestamp to by-pass browsers' cache
  69292. timeStampUsed = true;
  69293. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69294. }
  69295. xhr.open("GET", manifestURL, true);
  69296. xhr.addEventListener("load", function () {
  69297. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69298. try {
  69299. var manifestFile = JSON.parse(xhr.response);
  69300. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69301. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69302. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69303. _this.manifestVersionFound = manifestFile.version;
  69304. }
  69305. if (_this.callbackManifestChecked) {
  69306. _this.callbackManifestChecked(true);
  69307. }
  69308. }
  69309. catch (ex) {
  69310. noManifestFile();
  69311. }
  69312. }
  69313. else {
  69314. noManifestFile();
  69315. }
  69316. }, false);
  69317. xhr.addEventListener("error", function (event) {
  69318. if (timeStampUsed) {
  69319. timeStampUsed = false;
  69320. // Let's retry without the timeStamp
  69321. // It could fail when coupled with HTML5 Offline API
  69322. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69323. xhr.open("GET", retryManifestURL, true);
  69324. xhr.send();
  69325. }
  69326. else {
  69327. noManifestFile();
  69328. }
  69329. }, false);
  69330. try {
  69331. xhr.send();
  69332. }
  69333. catch (ex) {
  69334. BABYLON.Tools.Error("Error on XHR send request.");
  69335. this.callbackManifestChecked(false);
  69336. }
  69337. };
  69338. /**
  69339. * Open the database and make it available
  69340. * @param successCallback defines the callback to call on success
  69341. * @param errorCallback defines the callback to call on error
  69342. */
  69343. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69344. var _this = this;
  69345. var handleError = function () {
  69346. _this.isSupported = false;
  69347. if (errorCallback)
  69348. errorCallback();
  69349. };
  69350. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69351. // Your browser doesn't support IndexedDB
  69352. this.isSupported = false;
  69353. if (errorCallback)
  69354. errorCallback();
  69355. }
  69356. else {
  69357. // If the DB hasn't been opened or created yet
  69358. if (!this.db) {
  69359. this.hasReachedQuota = false;
  69360. this.isSupported = true;
  69361. var request = this.idbFactory.open("babylonjs", 1);
  69362. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69363. request.onerror = function (event) {
  69364. handleError();
  69365. };
  69366. // executes when a version change transaction cannot complete due to other active transactions
  69367. request.onblocked = function (event) {
  69368. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69369. handleError();
  69370. };
  69371. // DB has been opened successfully
  69372. request.onsuccess = function (event) {
  69373. _this.db = request.result;
  69374. successCallback();
  69375. };
  69376. // Initialization of the DB. Creating Scenes & Textures stores
  69377. request.onupgradeneeded = function (event) {
  69378. _this.db = (event.target).result;
  69379. if (_this.db) {
  69380. try {
  69381. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69382. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69383. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69384. }
  69385. catch (ex) {
  69386. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69387. handleError();
  69388. }
  69389. }
  69390. };
  69391. }
  69392. // DB has already been created and opened
  69393. else {
  69394. if (successCallback)
  69395. successCallback();
  69396. }
  69397. }
  69398. };
  69399. /**
  69400. * Loads an image from the database
  69401. * @param url defines the url to load from
  69402. * @param image defines the target DOM image
  69403. */
  69404. Database.prototype.loadImageFromDB = function (url, image) {
  69405. var _this = this;
  69406. var completeURL = Database._ReturnFullUrlLocation(url);
  69407. var saveAndLoadImage = function () {
  69408. if (!_this.hasReachedQuota && _this.db !== null) {
  69409. // the texture is not yet in the DB, let's try to save it
  69410. _this._saveImageIntoDBAsync(completeURL, image);
  69411. }
  69412. // If the texture is not in the DB and we've reached the DB quota limit
  69413. // let's load it directly from the web
  69414. else {
  69415. image.src = url;
  69416. }
  69417. };
  69418. if (!this.mustUpdateRessources) {
  69419. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69420. }
  69421. // First time we're download the images or update requested in the manifest file by a version change
  69422. else {
  69423. saveAndLoadImage();
  69424. }
  69425. };
  69426. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69427. if (this.isSupported && this.db !== null) {
  69428. var texture;
  69429. var transaction = this.db.transaction(["textures"]);
  69430. transaction.onabort = function (event) {
  69431. image.src = url;
  69432. };
  69433. transaction.oncomplete = function (event) {
  69434. var blobTextureURL;
  69435. if (texture) {
  69436. var URL = window.URL || window.webkitURL;
  69437. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69438. image.onerror = function () {
  69439. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69440. image.src = url;
  69441. };
  69442. image.src = blobTextureURL;
  69443. }
  69444. else {
  69445. notInDBCallback();
  69446. }
  69447. };
  69448. var getRequest = transaction.objectStore("textures").get(url);
  69449. getRequest.onsuccess = function (event) {
  69450. texture = (event.target).result;
  69451. };
  69452. getRequest.onerror = function (event) {
  69453. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69454. image.src = url;
  69455. };
  69456. }
  69457. else {
  69458. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69459. image.src = url;
  69460. }
  69461. };
  69462. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69463. var _this = this;
  69464. if (this.isSupported) {
  69465. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69466. var generateBlobUrl = function () {
  69467. var blobTextureURL;
  69468. if (blob) {
  69469. var URL = window.URL || window.webkitURL;
  69470. try {
  69471. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69472. }
  69473. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69474. catch (ex) {
  69475. blobTextureURL = URL.createObjectURL(blob);
  69476. }
  69477. }
  69478. if (blobTextureURL) {
  69479. image.src = blobTextureURL;
  69480. }
  69481. };
  69482. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69483. var xhr = new XMLHttpRequest(), blob;
  69484. xhr.open("GET", url, true);
  69485. xhr.responseType = "blob";
  69486. xhr.addEventListener("load", function () {
  69487. if (xhr.status === 200 && _this.db) {
  69488. // Blob as response (XHR2)
  69489. blob = xhr.response;
  69490. var transaction = _this.db.transaction(["textures"], "readwrite");
  69491. // the transaction could abort because of a QuotaExceededError error
  69492. transaction.onabort = function (event) {
  69493. try {
  69494. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69495. var srcElement = (event.srcElement || event.target);
  69496. var error = srcElement.error;
  69497. if (error && error.name === "QuotaExceededError") {
  69498. _this.hasReachedQuota = true;
  69499. }
  69500. }
  69501. catch (ex) { }
  69502. generateBlobUrl();
  69503. };
  69504. transaction.oncomplete = function (event) {
  69505. generateBlobUrl();
  69506. };
  69507. var newTexture = { textureUrl: url, data: blob };
  69508. try {
  69509. // Put the blob into the dabase
  69510. var addRequest = transaction.objectStore("textures").put(newTexture);
  69511. addRequest.onsuccess = function (event) {
  69512. };
  69513. addRequest.onerror = function (event) {
  69514. generateBlobUrl();
  69515. };
  69516. }
  69517. catch (ex) {
  69518. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69519. if (ex.code === 25) {
  69520. Database.IsUASupportingBlobStorage = false;
  69521. }
  69522. image.src = url;
  69523. }
  69524. }
  69525. else {
  69526. image.src = url;
  69527. }
  69528. }, false);
  69529. xhr.addEventListener("error", function (event) {
  69530. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69531. image.src = url;
  69532. }, false);
  69533. xhr.send();
  69534. }
  69535. else {
  69536. image.src = url;
  69537. }
  69538. }
  69539. else {
  69540. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69541. image.src = url;
  69542. }
  69543. };
  69544. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69545. var _this = this;
  69546. var updateVersion = function () {
  69547. // the version is not yet in the DB or we need to update it
  69548. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69549. };
  69550. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69551. };
  69552. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69553. var _this = this;
  69554. if (this.isSupported && this.db) {
  69555. var version;
  69556. try {
  69557. var transaction = this.db.transaction(["versions"]);
  69558. transaction.oncomplete = function (event) {
  69559. if (version) {
  69560. // If the version in the JSON file is different from the version in DB
  69561. if (_this.manifestVersionFound !== version.data) {
  69562. _this.mustUpdateRessources = true;
  69563. updateInDBCallback();
  69564. }
  69565. else {
  69566. callback(version.data);
  69567. }
  69568. }
  69569. // version was not found in DB
  69570. else {
  69571. _this.mustUpdateRessources = true;
  69572. updateInDBCallback();
  69573. }
  69574. };
  69575. transaction.onabort = function (event) {
  69576. callback(-1);
  69577. };
  69578. var getRequest = transaction.objectStore("versions").get(url);
  69579. getRequest.onsuccess = function (event) {
  69580. version = (event.target).result;
  69581. };
  69582. getRequest.onerror = function (event) {
  69583. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69584. callback(-1);
  69585. };
  69586. }
  69587. catch (ex) {
  69588. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69589. callback(-1);
  69590. }
  69591. }
  69592. else {
  69593. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69594. callback(-1);
  69595. }
  69596. };
  69597. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69598. var _this = this;
  69599. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69600. try {
  69601. // Open a transaction to the database
  69602. var transaction = this.db.transaction(["versions"], "readwrite");
  69603. // the transaction could abort because of a QuotaExceededError error
  69604. transaction.onabort = function (event) {
  69605. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69606. var error = event.srcElement['error'];
  69607. if (error && error.name === "QuotaExceededError") {
  69608. _this.hasReachedQuota = true;
  69609. }
  69610. }
  69611. catch (ex) { }
  69612. callback(-1);
  69613. };
  69614. transaction.oncomplete = function (event) {
  69615. callback(_this.manifestVersionFound);
  69616. };
  69617. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69618. // Put the scene into the database
  69619. var addRequest = transaction.objectStore("versions").put(newVersion);
  69620. addRequest.onsuccess = function (event) {
  69621. };
  69622. addRequest.onerror = function (event) {
  69623. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69624. };
  69625. }
  69626. catch (ex) {
  69627. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69628. callback(-1);
  69629. }
  69630. }
  69631. else {
  69632. callback(-1);
  69633. }
  69634. };
  69635. /**
  69636. * Loads a file from database
  69637. * @param url defines the URL to load from
  69638. * @param sceneLoaded defines a callback to call on success
  69639. * @param progressCallBack defines a callback to call when progress changed
  69640. * @param errorCallback defines a callback to call on error
  69641. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69642. */
  69643. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69644. var _this = this;
  69645. var completeUrl = Database._ReturnFullUrlLocation(url);
  69646. var saveAndLoadFile = function () {
  69647. // the scene is not yet in the DB, let's try to save it
  69648. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69649. };
  69650. this._checkVersionFromDB(completeUrl, function (version) {
  69651. if (version !== -1) {
  69652. if (!_this.mustUpdateRessources) {
  69653. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69654. }
  69655. else {
  69656. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  69657. }
  69658. }
  69659. else {
  69660. if (errorCallback) {
  69661. errorCallback();
  69662. }
  69663. }
  69664. });
  69665. };
  69666. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69667. if (this.isSupported && this.db) {
  69668. var targetStore;
  69669. if (url.indexOf(".babylon") !== -1) {
  69670. targetStore = "scenes";
  69671. }
  69672. else {
  69673. targetStore = "textures";
  69674. }
  69675. var file;
  69676. var transaction = this.db.transaction([targetStore]);
  69677. transaction.oncomplete = function (event) {
  69678. if (file) {
  69679. callback(file.data);
  69680. }
  69681. // file was not found in DB
  69682. else {
  69683. notInDBCallback();
  69684. }
  69685. };
  69686. transaction.onabort = function (event) {
  69687. notInDBCallback();
  69688. };
  69689. var getRequest = transaction.objectStore(targetStore).get(url);
  69690. getRequest.onsuccess = function (event) {
  69691. file = (event.target).result;
  69692. };
  69693. getRequest.onerror = function (event) {
  69694. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69695. notInDBCallback();
  69696. };
  69697. }
  69698. else {
  69699. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69700. callback();
  69701. }
  69702. };
  69703. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  69704. var _this = this;
  69705. if (this.isSupported) {
  69706. var targetStore;
  69707. if (url.indexOf(".babylon") !== -1) {
  69708. targetStore = "scenes";
  69709. }
  69710. else {
  69711. targetStore = "textures";
  69712. }
  69713. // Create XHR
  69714. var xhr = new XMLHttpRequest();
  69715. var fileData;
  69716. xhr.open("GET", url, true);
  69717. if (useArrayBuffer) {
  69718. xhr.responseType = "arraybuffer";
  69719. }
  69720. if (progressCallback) {
  69721. xhr.onprogress = progressCallback;
  69722. }
  69723. xhr.addEventListener("load", function () {
  69724. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  69725. // Blob as response (XHR2)
  69726. //fileData = xhr.responseText;
  69727. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69728. if (!_this.hasReachedQuota && _this.db) {
  69729. // Open a transaction to the database
  69730. var transaction = _this.db.transaction([targetStore], "readwrite");
  69731. // the transaction could abort because of a QuotaExceededError error
  69732. transaction.onabort = function (event) {
  69733. try {
  69734. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69735. var error = event.srcElement['error'];
  69736. if (error && error.name === "QuotaExceededError") {
  69737. _this.hasReachedQuota = true;
  69738. }
  69739. }
  69740. catch (ex) { }
  69741. callback(fileData);
  69742. };
  69743. transaction.oncomplete = function (event) {
  69744. callback(fileData);
  69745. };
  69746. var newFile;
  69747. if (targetStore === "scenes") {
  69748. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69749. }
  69750. else {
  69751. newFile = { textureUrl: url, data: fileData };
  69752. }
  69753. try {
  69754. // Put the scene into the database
  69755. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69756. addRequest.onsuccess = function (event) {
  69757. };
  69758. addRequest.onerror = function (event) {
  69759. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69760. };
  69761. }
  69762. catch (ex) {
  69763. callback(fileData);
  69764. }
  69765. }
  69766. else {
  69767. callback(fileData);
  69768. }
  69769. }
  69770. else {
  69771. if (xhr.status >= 400 && errorCallback) {
  69772. errorCallback(xhr);
  69773. }
  69774. else {
  69775. callback();
  69776. }
  69777. }
  69778. }, false);
  69779. xhr.addEventListener("error", function (event) {
  69780. BABYLON.Tools.Error("error on XHR request.");
  69781. callback();
  69782. }, false);
  69783. xhr.send();
  69784. }
  69785. else {
  69786. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69787. callback();
  69788. }
  69789. };
  69790. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69791. Database.IsUASupportingBlobStorage = true;
  69792. /** Gets a boolean indicating if Database storate is enabled */
  69793. Database.IDBStorageEnabled = true;
  69794. Database._ParseURL = function (url) {
  69795. var a = document.createElement('a');
  69796. a.href = url;
  69797. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69798. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69799. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69800. return absLocation;
  69801. };
  69802. Database._ReturnFullUrlLocation = function (url) {
  69803. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69804. return (Database._ParseURL(window.location.href) + url);
  69805. }
  69806. else {
  69807. return url;
  69808. }
  69809. };
  69810. return Database;
  69811. }());
  69812. BABYLON.Database = Database;
  69813. })(BABYLON || (BABYLON = {}));
  69814. //# sourceMappingURL=babylon.database.js.map
  69815. var BABYLON;
  69816. (function (BABYLON) {
  69817. var FresnelParameters = /** @class */ (function () {
  69818. function FresnelParameters() {
  69819. this._isEnabled = true;
  69820. this.leftColor = BABYLON.Color3.White();
  69821. this.rightColor = BABYLON.Color3.Black();
  69822. this.bias = 0;
  69823. this.power = 1;
  69824. }
  69825. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69826. get: function () {
  69827. return this._isEnabled;
  69828. },
  69829. set: function (value) {
  69830. if (this._isEnabled === value) {
  69831. return;
  69832. }
  69833. this._isEnabled = value;
  69834. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69835. },
  69836. enumerable: true,
  69837. configurable: true
  69838. });
  69839. FresnelParameters.prototype.clone = function () {
  69840. var newFresnelParameters = new FresnelParameters();
  69841. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69842. return newFresnelParameters;
  69843. };
  69844. FresnelParameters.prototype.serialize = function () {
  69845. var serializationObject = {};
  69846. serializationObject.isEnabled = this.isEnabled;
  69847. serializationObject.leftColor = this.leftColor.asArray();
  69848. serializationObject.rightColor = this.rightColor.asArray();
  69849. serializationObject.bias = this.bias;
  69850. serializationObject.power = this.power;
  69851. return serializationObject;
  69852. };
  69853. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69854. var fresnelParameters = new FresnelParameters();
  69855. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69856. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69857. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69858. fresnelParameters.bias = parsedFresnelParameters.bias;
  69859. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69860. return fresnelParameters;
  69861. };
  69862. return FresnelParameters;
  69863. }());
  69864. BABYLON.FresnelParameters = FresnelParameters;
  69865. })(BABYLON || (BABYLON = {}));
  69866. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69867. var BABYLON;
  69868. (function (BABYLON) {
  69869. var MultiMaterial = /** @class */ (function (_super) {
  69870. __extends(MultiMaterial, _super);
  69871. function MultiMaterial(name, scene) {
  69872. var _this = _super.call(this, name, scene, true) || this;
  69873. scene.multiMaterials.push(_this);
  69874. _this.subMaterials = new Array();
  69875. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69876. return _this;
  69877. }
  69878. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69879. get: function () {
  69880. return this._subMaterials;
  69881. },
  69882. set: function (value) {
  69883. this._subMaterials = value;
  69884. this._hookArray(value);
  69885. },
  69886. enumerable: true,
  69887. configurable: true
  69888. });
  69889. MultiMaterial.prototype._hookArray = function (array) {
  69890. var _this = this;
  69891. var oldPush = array.push;
  69892. array.push = function () {
  69893. var items = [];
  69894. for (var _i = 0; _i < arguments.length; _i++) {
  69895. items[_i] = arguments[_i];
  69896. }
  69897. var result = oldPush.apply(array, items);
  69898. _this._markAllSubMeshesAsTexturesDirty();
  69899. return result;
  69900. };
  69901. var oldSplice = array.splice;
  69902. array.splice = function (index, deleteCount) {
  69903. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69904. _this._markAllSubMeshesAsTexturesDirty();
  69905. return deleted;
  69906. };
  69907. };
  69908. // Properties
  69909. MultiMaterial.prototype.getSubMaterial = function (index) {
  69910. if (index < 0 || index >= this.subMaterials.length) {
  69911. return this.getScene().defaultMaterial;
  69912. }
  69913. return this.subMaterials[index];
  69914. };
  69915. MultiMaterial.prototype.getActiveTextures = function () {
  69916. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69917. if (subMaterial) {
  69918. return subMaterial.getActiveTextures();
  69919. }
  69920. else {
  69921. return [];
  69922. }
  69923. }));
  69924. var _a;
  69925. };
  69926. // Methods
  69927. MultiMaterial.prototype.getClassName = function () {
  69928. return "MultiMaterial";
  69929. };
  69930. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69931. for (var index = 0; index < this.subMaterials.length; index++) {
  69932. var subMaterial = this.subMaterials[index];
  69933. if (subMaterial) {
  69934. if (subMaterial.storeEffectOnSubMeshes) {
  69935. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69936. return false;
  69937. }
  69938. continue;
  69939. }
  69940. if (!subMaterial.isReady(mesh)) {
  69941. return false;
  69942. }
  69943. }
  69944. }
  69945. return true;
  69946. };
  69947. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69948. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69949. for (var index = 0; index < this.subMaterials.length; index++) {
  69950. var subMaterial = null;
  69951. var current = this.subMaterials[index];
  69952. if (cloneChildren && current) {
  69953. subMaterial = current.clone(name + "-" + current.name);
  69954. }
  69955. else {
  69956. subMaterial = this.subMaterials[index];
  69957. }
  69958. newMultiMaterial.subMaterials.push(subMaterial);
  69959. }
  69960. return newMultiMaterial;
  69961. };
  69962. MultiMaterial.prototype.serialize = function () {
  69963. var serializationObject = {};
  69964. serializationObject.name = this.name;
  69965. serializationObject.id = this.id;
  69966. if (BABYLON.Tags) {
  69967. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69968. }
  69969. serializationObject.materials = [];
  69970. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69971. var subMat = this.subMaterials[matIndex];
  69972. if (subMat) {
  69973. serializationObject.materials.push(subMat.id);
  69974. }
  69975. else {
  69976. serializationObject.materials.push(null);
  69977. }
  69978. }
  69979. return serializationObject;
  69980. };
  69981. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69982. var scene = this.getScene();
  69983. if (!scene) {
  69984. return;
  69985. }
  69986. var index = scene.multiMaterials.indexOf(this);
  69987. if (index >= 0) {
  69988. scene.multiMaterials.splice(index, 1);
  69989. }
  69990. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69991. };
  69992. return MultiMaterial;
  69993. }(BABYLON.Material));
  69994. BABYLON.MultiMaterial = MultiMaterial;
  69995. })(BABYLON || (BABYLON = {}));
  69996. //# sourceMappingURL=babylon.multiMaterial.js.map
  69997. var BABYLON;
  69998. (function (BABYLON) {
  69999. var FreeCameraTouchInput = /** @class */ (function () {
  70000. function FreeCameraTouchInput() {
  70001. this._offsetX = null;
  70002. this._offsetY = null;
  70003. this._pointerPressed = new Array();
  70004. this.touchAngularSensibility = 200000.0;
  70005. this.touchMoveSensibility = 250.0;
  70006. }
  70007. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70008. var _this = this;
  70009. var previousPosition = null;
  70010. if (this._pointerInput === undefined) {
  70011. this._onLostFocus = function (evt) {
  70012. _this._offsetX = null;
  70013. _this._offsetY = null;
  70014. };
  70015. this._pointerInput = function (p, s) {
  70016. var evt = p.event;
  70017. if (evt.pointerType === "mouse") {
  70018. return;
  70019. }
  70020. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70021. if (!noPreventDefault) {
  70022. evt.preventDefault();
  70023. }
  70024. _this._pointerPressed.push(evt.pointerId);
  70025. if (_this._pointerPressed.length !== 1) {
  70026. return;
  70027. }
  70028. previousPosition = {
  70029. x: evt.clientX,
  70030. y: evt.clientY
  70031. };
  70032. }
  70033. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70034. if (!noPreventDefault) {
  70035. evt.preventDefault();
  70036. }
  70037. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70038. if (index === -1) {
  70039. return;
  70040. }
  70041. _this._pointerPressed.splice(index, 1);
  70042. if (index != 0) {
  70043. return;
  70044. }
  70045. previousPosition = null;
  70046. _this._offsetX = null;
  70047. _this._offsetY = null;
  70048. }
  70049. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70050. if (!noPreventDefault) {
  70051. evt.preventDefault();
  70052. }
  70053. if (!previousPosition) {
  70054. return;
  70055. }
  70056. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70057. if (index != 0) {
  70058. return;
  70059. }
  70060. _this._offsetX = evt.clientX - previousPosition.x;
  70061. _this._offsetY = -(evt.clientY - previousPosition.y);
  70062. }
  70063. };
  70064. }
  70065. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70066. if (this._onLostFocus) {
  70067. element.addEventListener("blur", this._onLostFocus);
  70068. }
  70069. };
  70070. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70071. if (this._pointerInput && element) {
  70072. if (this._observer) {
  70073. this.camera.getScene().onPointerObservable.remove(this._observer);
  70074. this._observer = null;
  70075. }
  70076. if (this._onLostFocus) {
  70077. element.removeEventListener("blur", this._onLostFocus);
  70078. this._onLostFocus = null;
  70079. }
  70080. this._pointerPressed = [];
  70081. this._offsetX = null;
  70082. this._offsetY = null;
  70083. }
  70084. };
  70085. FreeCameraTouchInput.prototype.checkInputs = function () {
  70086. if (this._offsetX && this._offsetY) {
  70087. var camera = this.camera;
  70088. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70089. if (this._pointerPressed.length > 1) {
  70090. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70091. }
  70092. else {
  70093. var speed = camera._computeLocalCameraSpeed();
  70094. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70095. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70096. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70097. }
  70098. }
  70099. };
  70100. FreeCameraTouchInput.prototype.getClassName = function () {
  70101. return "FreeCameraTouchInput";
  70102. };
  70103. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70104. return "touch";
  70105. };
  70106. __decorate([
  70107. BABYLON.serialize()
  70108. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70109. __decorate([
  70110. BABYLON.serialize()
  70111. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70112. return FreeCameraTouchInput;
  70113. }());
  70114. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70115. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70116. })(BABYLON || (BABYLON = {}));
  70117. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70118. var BABYLON;
  70119. (function (BABYLON) {
  70120. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  70121. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  70122. });
  70123. // We're mainly based on the logic defined into the FreeCamera code
  70124. var TouchCamera = /** @class */ (function (_super) {
  70125. __extends(TouchCamera, _super);
  70126. //-- end properties for backward compatibility for inputs
  70127. function TouchCamera(name, position, scene) {
  70128. var _this = _super.call(this, name, position, scene) || this;
  70129. _this.inputs.addTouch();
  70130. _this._setupInputs();
  70131. return _this;
  70132. }
  70133. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70134. //-- Begin properties for backward compatibility for inputs
  70135. get: function () {
  70136. var touch = this.inputs.attached["touch"];
  70137. if (touch)
  70138. return touch.touchAngularSensibility;
  70139. return 0;
  70140. },
  70141. set: function (value) {
  70142. var touch = this.inputs.attached["touch"];
  70143. if (touch)
  70144. touch.touchAngularSensibility = value;
  70145. },
  70146. enumerable: true,
  70147. configurable: true
  70148. });
  70149. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70150. get: function () {
  70151. var touch = this.inputs.attached["touch"];
  70152. if (touch)
  70153. return touch.touchMoveSensibility;
  70154. return 0;
  70155. },
  70156. set: function (value) {
  70157. var touch = this.inputs.attached["touch"];
  70158. if (touch)
  70159. touch.touchMoveSensibility = value;
  70160. },
  70161. enumerable: true,
  70162. configurable: true
  70163. });
  70164. TouchCamera.prototype.getClassName = function () {
  70165. return "TouchCamera";
  70166. };
  70167. TouchCamera.prototype._setupInputs = function () {
  70168. var mouse = this.inputs.attached["mouse"];
  70169. if (mouse) {
  70170. mouse.touchEnabled = false;
  70171. }
  70172. };
  70173. return TouchCamera;
  70174. }(BABYLON.FreeCamera));
  70175. BABYLON.TouchCamera = TouchCamera;
  70176. })(BABYLON || (BABYLON = {}));
  70177. //# sourceMappingURL=babylon.touchCamera.js.map
  70178. var BABYLON;
  70179. (function (BABYLON) {
  70180. var ProceduralTexture = /** @class */ (function (_super) {
  70181. __extends(ProceduralTexture, _super);
  70182. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70183. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70185. if (isCube === void 0) { isCube = false; }
  70186. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70187. _this.isCube = isCube;
  70188. _this.isEnabled = true;
  70189. _this._currentRefreshId = -1;
  70190. _this._refreshRate = 1;
  70191. _this._vertexBuffers = {};
  70192. _this._uniforms = new Array();
  70193. _this._samplers = new Array();
  70194. _this._textures = {};
  70195. _this._floats = {};
  70196. _this._floatsArrays = {};
  70197. _this._colors3 = {};
  70198. _this._colors4 = {};
  70199. _this._vectors2 = {};
  70200. _this._vectors3 = {};
  70201. _this._matrices = {};
  70202. _this._fallbackTextureUsed = false;
  70203. scene.proceduralTextures.push(_this);
  70204. _this._engine = scene.getEngine();
  70205. _this.name = name;
  70206. _this.isRenderTarget = true;
  70207. _this._size = size;
  70208. _this._generateMipMaps = generateMipMaps;
  70209. _this.setFragment(fragment);
  70210. _this._fallbackTexture = fallbackTexture;
  70211. if (isCube) {
  70212. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70213. _this.setFloat("face", 0);
  70214. }
  70215. else {
  70216. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70217. }
  70218. // VBO
  70219. var vertices = [];
  70220. vertices.push(1, 1);
  70221. vertices.push(-1, 1);
  70222. vertices.push(-1, -1);
  70223. vertices.push(1, -1);
  70224. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70225. _this._createIndexBuffer();
  70226. return _this;
  70227. }
  70228. ProceduralTexture.prototype._createIndexBuffer = function () {
  70229. var engine = this._engine;
  70230. // Indices
  70231. var indices = [];
  70232. indices.push(0);
  70233. indices.push(1);
  70234. indices.push(2);
  70235. indices.push(0);
  70236. indices.push(2);
  70237. indices.push(3);
  70238. this._indexBuffer = engine.createIndexBuffer(indices);
  70239. };
  70240. ProceduralTexture.prototype._rebuild = function () {
  70241. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70242. if (vb) {
  70243. vb._rebuild();
  70244. }
  70245. this._createIndexBuffer();
  70246. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70247. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70248. }
  70249. };
  70250. ProceduralTexture.prototype.reset = function () {
  70251. if (this._effect === undefined) {
  70252. return;
  70253. }
  70254. var engine = this._engine;
  70255. engine._releaseEffect(this._effect);
  70256. };
  70257. ProceduralTexture.prototype.isReady = function () {
  70258. var _this = this;
  70259. var engine = this._engine;
  70260. var shaders;
  70261. if (!this._fragment) {
  70262. return false;
  70263. }
  70264. if (this._fallbackTextureUsed) {
  70265. return true;
  70266. }
  70267. if (this._fragment.fragmentElement !== undefined) {
  70268. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70269. }
  70270. else {
  70271. shaders = { vertex: "procedural", fragment: this._fragment };
  70272. }
  70273. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70274. _this.releaseInternalTexture();
  70275. if (_this._fallbackTexture) {
  70276. _this._texture = _this._fallbackTexture._texture;
  70277. if (_this._texture) {
  70278. _this._texture.incrementReferences();
  70279. }
  70280. }
  70281. _this._fallbackTextureUsed = true;
  70282. });
  70283. return this._effect.isReady();
  70284. };
  70285. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70286. this._currentRefreshId = -1;
  70287. };
  70288. ProceduralTexture.prototype.setFragment = function (fragment) {
  70289. this._fragment = fragment;
  70290. };
  70291. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70292. get: function () {
  70293. return this._refreshRate;
  70294. },
  70295. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70296. set: function (value) {
  70297. this._refreshRate = value;
  70298. this.resetRefreshCounter();
  70299. },
  70300. enumerable: true,
  70301. configurable: true
  70302. });
  70303. ProceduralTexture.prototype._shouldRender = function () {
  70304. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70305. return false;
  70306. }
  70307. if (this._fallbackTextureUsed) {
  70308. return false;
  70309. }
  70310. if (this._currentRefreshId === -1) { // At least render once
  70311. this._currentRefreshId = 1;
  70312. return true;
  70313. }
  70314. if (this.refreshRate === this._currentRefreshId) {
  70315. this._currentRefreshId = 1;
  70316. return true;
  70317. }
  70318. this._currentRefreshId++;
  70319. return false;
  70320. };
  70321. ProceduralTexture.prototype.getRenderSize = function () {
  70322. return this._size;
  70323. };
  70324. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70325. if (this._fallbackTextureUsed) {
  70326. return;
  70327. }
  70328. this.releaseInternalTexture();
  70329. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70330. // Update properties
  70331. this._size = size;
  70332. this._generateMipMaps = generateMipMaps;
  70333. };
  70334. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70335. if (this._uniforms.indexOf(uniformName) === -1) {
  70336. this._uniforms.push(uniformName);
  70337. }
  70338. };
  70339. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70340. if (this._samplers.indexOf(name) === -1) {
  70341. this._samplers.push(name);
  70342. }
  70343. this._textures[name] = texture;
  70344. return this;
  70345. };
  70346. ProceduralTexture.prototype.setFloat = function (name, value) {
  70347. this._checkUniform(name);
  70348. this._floats[name] = value;
  70349. return this;
  70350. };
  70351. ProceduralTexture.prototype.setFloats = function (name, value) {
  70352. this._checkUniform(name);
  70353. this._floatsArrays[name] = value;
  70354. return this;
  70355. };
  70356. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70357. this._checkUniform(name);
  70358. this._colors3[name] = value;
  70359. return this;
  70360. };
  70361. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70362. this._checkUniform(name);
  70363. this._colors4[name] = value;
  70364. return this;
  70365. };
  70366. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70367. this._checkUniform(name);
  70368. this._vectors2[name] = value;
  70369. return this;
  70370. };
  70371. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70372. this._checkUniform(name);
  70373. this._vectors3[name] = value;
  70374. return this;
  70375. };
  70376. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70377. this._checkUniform(name);
  70378. this._matrices[name] = value;
  70379. return this;
  70380. };
  70381. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70382. var scene = this.getScene();
  70383. if (!scene) {
  70384. return;
  70385. }
  70386. var engine = this._engine;
  70387. // Render
  70388. engine.enableEffect(this._effect);
  70389. engine.setState(false);
  70390. // Texture
  70391. for (var name in this._textures) {
  70392. this._effect.setTexture(name, this._textures[name]);
  70393. }
  70394. // Float
  70395. for (name in this._floats) {
  70396. this._effect.setFloat(name, this._floats[name]);
  70397. }
  70398. // Floats
  70399. for (name in this._floatsArrays) {
  70400. this._effect.setArray(name, this._floatsArrays[name]);
  70401. }
  70402. // Color3
  70403. for (name in this._colors3) {
  70404. this._effect.setColor3(name, this._colors3[name]);
  70405. }
  70406. // Color4
  70407. for (name in this._colors4) {
  70408. var color = this._colors4[name];
  70409. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70410. }
  70411. // Vector2
  70412. for (name in this._vectors2) {
  70413. this._effect.setVector2(name, this._vectors2[name]);
  70414. }
  70415. // Vector3
  70416. for (name in this._vectors3) {
  70417. this._effect.setVector3(name, this._vectors3[name]);
  70418. }
  70419. // Matrix
  70420. for (name in this._matrices) {
  70421. this._effect.setMatrix(name, this._matrices[name]);
  70422. }
  70423. if (!this._texture) {
  70424. return;
  70425. }
  70426. if (this.isCube) {
  70427. for (var face = 0; face < 6; face++) {
  70428. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70429. // VBOs
  70430. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70431. this._effect.setFloat("face", face);
  70432. // Clear
  70433. engine.clear(scene.clearColor, true, true, true);
  70434. // Draw order
  70435. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70436. // Mipmaps
  70437. if (face === 5) {
  70438. engine.generateMipMapsForCubemap(this._texture);
  70439. }
  70440. }
  70441. }
  70442. else {
  70443. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70444. // VBOs
  70445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70446. // Clear
  70447. engine.clear(scene.clearColor, true, true, true);
  70448. // Draw order
  70449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70450. }
  70451. // Unbind
  70452. engine.unBindFramebuffer(this._texture, this.isCube);
  70453. if (this.onGenerated) {
  70454. this.onGenerated();
  70455. }
  70456. };
  70457. ProceduralTexture.prototype.clone = function () {
  70458. var textureSize = this.getSize();
  70459. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70460. // Base texture
  70461. newTexture.hasAlpha = this.hasAlpha;
  70462. newTexture.level = this.level;
  70463. // RenderTarget Texture
  70464. newTexture.coordinatesMode = this.coordinatesMode;
  70465. return newTexture;
  70466. };
  70467. ProceduralTexture.prototype.dispose = function () {
  70468. var scene = this.getScene();
  70469. if (!scene) {
  70470. return;
  70471. }
  70472. var index = scene.proceduralTextures.indexOf(this);
  70473. if (index >= 0) {
  70474. scene.proceduralTextures.splice(index, 1);
  70475. }
  70476. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70477. if (vertexBuffer) {
  70478. vertexBuffer.dispose();
  70479. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70480. }
  70481. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70482. this._indexBuffer = null;
  70483. }
  70484. _super.prototype.dispose.call(this);
  70485. };
  70486. __decorate([
  70487. BABYLON.serialize()
  70488. ], ProceduralTexture.prototype, "_size", void 0);
  70489. __decorate([
  70490. BABYLON.serialize()
  70491. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70492. __decorate([
  70493. BABYLON.serialize()
  70494. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70495. __decorate([
  70496. BABYLON.serialize()
  70497. ], ProceduralTexture.prototype, "refreshRate", null);
  70498. return ProceduralTexture;
  70499. }(BABYLON.Texture));
  70500. BABYLON.ProceduralTexture = ProceduralTexture;
  70501. })(BABYLON || (BABYLON = {}));
  70502. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70503. var BABYLON;
  70504. (function (BABYLON) {
  70505. var CustomProceduralTexture = /** @class */ (function (_super) {
  70506. __extends(CustomProceduralTexture, _super);
  70507. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70508. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70509. _this._animate = true;
  70510. _this._time = 0;
  70511. _this._texturePath = texturePath;
  70512. //Try to load json
  70513. _this.loadJson(texturePath);
  70514. _this.refreshRate = 1;
  70515. return _this;
  70516. }
  70517. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70518. var _this = this;
  70519. var noConfigFile = function () {
  70520. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70521. try {
  70522. _this.setFragment(_this._texturePath);
  70523. }
  70524. catch (ex) {
  70525. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70526. }
  70527. };
  70528. var configFileUrl = jsonUrl + "/config.json";
  70529. var xhr = new XMLHttpRequest();
  70530. xhr.open("GET", configFileUrl, true);
  70531. xhr.addEventListener("load", function () {
  70532. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70533. try {
  70534. _this._config = JSON.parse(xhr.response);
  70535. _this.updateShaderUniforms();
  70536. _this.updateTextures();
  70537. _this.setFragment(_this._texturePath + "/custom");
  70538. _this._animate = _this._config.animate;
  70539. _this.refreshRate = _this._config.refreshrate;
  70540. }
  70541. catch (ex) {
  70542. noConfigFile();
  70543. }
  70544. }
  70545. else {
  70546. noConfigFile();
  70547. }
  70548. }, false);
  70549. xhr.addEventListener("error", function () {
  70550. noConfigFile();
  70551. }, false);
  70552. try {
  70553. xhr.send();
  70554. }
  70555. catch (ex) {
  70556. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70557. }
  70558. };
  70559. CustomProceduralTexture.prototype.isReady = function () {
  70560. if (!_super.prototype.isReady.call(this)) {
  70561. return false;
  70562. }
  70563. for (var name in this._textures) {
  70564. var texture = this._textures[name];
  70565. if (!texture.isReady()) {
  70566. return false;
  70567. }
  70568. }
  70569. return true;
  70570. };
  70571. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70572. var scene = this.getScene();
  70573. if (this._animate && scene) {
  70574. this._time += scene.getAnimationRatio() * 0.03;
  70575. this.updateShaderUniforms();
  70576. }
  70577. _super.prototype.render.call(this, useCameraPostProcess);
  70578. };
  70579. CustomProceduralTexture.prototype.updateTextures = function () {
  70580. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70581. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70582. }
  70583. };
  70584. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70585. if (this._config) {
  70586. for (var j = 0; j < this._config.uniforms.length; j++) {
  70587. var uniform = this._config.uniforms[j];
  70588. switch (uniform.type) {
  70589. case "float":
  70590. this.setFloat(uniform.name, uniform.value);
  70591. break;
  70592. case "color3":
  70593. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70594. break;
  70595. case "color4":
  70596. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70597. break;
  70598. case "vector2":
  70599. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70600. break;
  70601. case "vector3":
  70602. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70603. break;
  70604. }
  70605. }
  70606. }
  70607. this.setFloat("time", this._time);
  70608. };
  70609. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70610. get: function () {
  70611. return this._animate;
  70612. },
  70613. set: function (value) {
  70614. this._animate = value;
  70615. },
  70616. enumerable: true,
  70617. configurable: true
  70618. });
  70619. return CustomProceduralTexture;
  70620. }(BABYLON.ProceduralTexture));
  70621. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70622. })(BABYLON || (BABYLON = {}));
  70623. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70624. var BABYLON;
  70625. (function (BABYLON) {
  70626. var FreeCameraGamepadInput = /** @class */ (function () {
  70627. function FreeCameraGamepadInput() {
  70628. this.gamepadAngularSensibility = 200;
  70629. this.gamepadMoveSensibility = 40;
  70630. // private members
  70631. this._cameraTransform = BABYLON.Matrix.Identity();
  70632. this._deltaTransform = BABYLON.Vector3.Zero();
  70633. this._vector3 = BABYLON.Vector3.Zero();
  70634. this._vector2 = BABYLON.Vector2.Zero();
  70635. }
  70636. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70637. var _this = this;
  70638. var manager = this.camera.getScene().gamepadManager;
  70639. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70640. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70641. // prioritize XBOX gamepads.
  70642. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70643. _this.gamepad = gamepad;
  70644. }
  70645. }
  70646. });
  70647. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70648. if (_this.gamepad === gamepad) {
  70649. _this.gamepad = null;
  70650. }
  70651. });
  70652. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70653. };
  70654. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70655. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70656. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70657. this.gamepad = null;
  70658. };
  70659. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70660. if (this.gamepad && this.gamepad.leftStick) {
  70661. var camera = this.camera;
  70662. var LSValues = this.gamepad.leftStick;
  70663. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70664. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70665. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70666. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70667. var RSValues = this.gamepad.rightStick;
  70668. if (RSValues) {
  70669. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70670. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70671. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70672. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70673. }
  70674. else {
  70675. RSValues = { x: 0, y: 0 };
  70676. }
  70677. if (!camera.rotationQuaternion) {
  70678. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70679. }
  70680. else {
  70681. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70682. }
  70683. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70684. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70685. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70686. camera.cameraDirection.addInPlace(this._deltaTransform);
  70687. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70688. camera.cameraRotation.addInPlace(this._vector2);
  70689. }
  70690. };
  70691. FreeCameraGamepadInput.prototype.getClassName = function () {
  70692. return "FreeCameraGamepadInput";
  70693. };
  70694. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70695. return "gamepad";
  70696. };
  70697. __decorate([
  70698. BABYLON.serialize()
  70699. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70700. __decorate([
  70701. BABYLON.serialize()
  70702. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70703. return FreeCameraGamepadInput;
  70704. }());
  70705. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70706. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70707. })(BABYLON || (BABYLON = {}));
  70708. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70709. var BABYLON;
  70710. (function (BABYLON) {
  70711. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70712. function ArcRotateCameraGamepadInput() {
  70713. this.gamepadRotationSensibility = 80;
  70714. this.gamepadMoveSensibility = 40;
  70715. }
  70716. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70717. var _this = this;
  70718. var manager = this.camera.getScene().gamepadManager;
  70719. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70720. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70721. // prioritize XBOX gamepads.
  70722. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70723. _this.gamepad = gamepad;
  70724. }
  70725. }
  70726. });
  70727. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70728. if (_this.gamepad === gamepad) {
  70729. _this.gamepad = null;
  70730. }
  70731. });
  70732. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70733. };
  70734. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70735. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70736. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70737. this.gamepad = null;
  70738. };
  70739. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70740. if (this.gamepad) {
  70741. var camera = this.camera;
  70742. var RSValues = this.gamepad.rightStick;
  70743. if (RSValues) {
  70744. if (RSValues.x != 0) {
  70745. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70746. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70747. camera.inertialAlphaOffset += normalizedRX;
  70748. }
  70749. }
  70750. if (RSValues.y != 0) {
  70751. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70752. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70753. camera.inertialBetaOffset += normalizedRY;
  70754. }
  70755. }
  70756. }
  70757. var LSValues = this.gamepad.leftStick;
  70758. if (LSValues && LSValues.y != 0) {
  70759. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70760. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70761. this.camera.inertialRadiusOffset -= normalizedLY;
  70762. }
  70763. }
  70764. }
  70765. };
  70766. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70767. return "ArcRotateCameraGamepadInput";
  70768. };
  70769. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70770. return "gamepad";
  70771. };
  70772. __decorate([
  70773. BABYLON.serialize()
  70774. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70775. __decorate([
  70776. BABYLON.serialize()
  70777. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70778. return ArcRotateCameraGamepadInput;
  70779. }());
  70780. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70781. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70782. })(BABYLON || (BABYLON = {}));
  70783. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70784. var BABYLON;
  70785. (function (BABYLON) {
  70786. var GamepadManager = /** @class */ (function () {
  70787. function GamepadManager(_scene) {
  70788. var _this = this;
  70789. this._scene = _scene;
  70790. this._babylonGamepads = [];
  70791. this._oneGamepadConnected = false;
  70792. this._isMonitoring = false;
  70793. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70794. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70795. this._gamepadEventSupported = false;
  70796. }
  70797. else {
  70798. this._gamepadEventSupported = 'GamepadEvent' in window;
  70799. this._gamepadSupport = (navigator.getGamepads ||
  70800. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70801. }
  70802. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70803. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70804. for (var i in _this._babylonGamepads) {
  70805. var gamepad = _this._babylonGamepads[i];
  70806. if (gamepad && gamepad._isConnected) {
  70807. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70808. }
  70809. }
  70810. });
  70811. this._onGamepadConnectedEvent = function (evt) {
  70812. var gamepad = evt.gamepad;
  70813. if (gamepad.index in _this._babylonGamepads) {
  70814. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70815. return;
  70816. }
  70817. }
  70818. var newGamepad;
  70819. if (_this._babylonGamepads[gamepad.index]) {
  70820. newGamepad = _this._babylonGamepads[gamepad.index];
  70821. newGamepad.browserGamepad = gamepad;
  70822. newGamepad._isConnected = true;
  70823. }
  70824. else {
  70825. newGamepad = _this._addNewGamepad(gamepad);
  70826. }
  70827. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70828. _this._startMonitoringGamepads();
  70829. };
  70830. this._onGamepadDisconnectedEvent = function (evt) {
  70831. var gamepad = evt.gamepad;
  70832. // Remove the gamepad from the list of gamepads to monitor.
  70833. for (var i in _this._babylonGamepads) {
  70834. if (_this._babylonGamepads[i].index === gamepad.index) {
  70835. var disconnectedGamepad = _this._babylonGamepads[i];
  70836. disconnectedGamepad._isConnected = false;
  70837. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70838. break;
  70839. }
  70840. }
  70841. };
  70842. if (this._gamepadSupport) {
  70843. //first add already-connected gamepads
  70844. this._updateGamepadObjects();
  70845. if (this._babylonGamepads.length) {
  70846. this._startMonitoringGamepads();
  70847. }
  70848. // Checking if the gamepad connected event is supported (like in Firefox)
  70849. if (this._gamepadEventSupported) {
  70850. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70851. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70852. }
  70853. else {
  70854. this._startMonitoringGamepads();
  70855. }
  70856. }
  70857. }
  70858. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70859. get: function () {
  70860. return this._babylonGamepads;
  70861. },
  70862. enumerable: true,
  70863. configurable: true
  70864. });
  70865. GamepadManager.prototype.getGamepadByType = function (type) {
  70866. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70867. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70868. var gamepad = _a[_i];
  70869. if (gamepad && gamepad.type === type) {
  70870. return gamepad;
  70871. }
  70872. }
  70873. return null;
  70874. };
  70875. GamepadManager.prototype.dispose = function () {
  70876. if (this._gamepadEventSupported) {
  70877. if (this._onGamepadConnectedEvent) {
  70878. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70879. }
  70880. if (this._onGamepadDisconnectedEvent) {
  70881. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70882. }
  70883. this._onGamepadConnectedEvent = null;
  70884. this._onGamepadDisconnectedEvent = null;
  70885. }
  70886. this._babylonGamepads.forEach(function (gamepad) {
  70887. gamepad.dispose();
  70888. });
  70889. this.onGamepadConnectedObservable.clear();
  70890. this.onGamepadDisconnectedObservable.clear();
  70891. this._oneGamepadConnected = false;
  70892. this._stopMonitoringGamepads();
  70893. this._babylonGamepads = [];
  70894. };
  70895. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70896. if (!this._oneGamepadConnected) {
  70897. this._oneGamepadConnected = true;
  70898. }
  70899. var newGamepad;
  70900. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70901. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70902. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70903. }
  70904. // if pose is supported, use the (WebVR) pose enabled controller
  70905. else if (gamepad.pose) {
  70906. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70907. }
  70908. else {
  70909. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70910. }
  70911. this._babylonGamepads[newGamepad.index] = newGamepad;
  70912. return newGamepad;
  70913. };
  70914. GamepadManager.prototype._startMonitoringGamepads = function () {
  70915. if (!this._isMonitoring) {
  70916. this._isMonitoring = true;
  70917. //back-comp
  70918. if (!this._scene) {
  70919. this._checkGamepadsStatus();
  70920. }
  70921. }
  70922. };
  70923. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70924. this._isMonitoring = false;
  70925. };
  70926. GamepadManager.prototype._checkGamepadsStatus = function () {
  70927. var _this = this;
  70928. // Hack to be compatible Chrome
  70929. this._updateGamepadObjects();
  70930. for (var i in this._babylonGamepads) {
  70931. var gamepad = this._babylonGamepads[i];
  70932. if (!gamepad || !gamepad.isConnected) {
  70933. continue;
  70934. }
  70935. gamepad.update();
  70936. }
  70937. if (this._isMonitoring && !this._scene) {
  70938. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70939. }
  70940. };
  70941. // This function is called only on Chrome, which does not properly support
  70942. // connection/disconnection events and forces you to recopy again the gamepad object
  70943. GamepadManager.prototype._updateGamepadObjects = function () {
  70944. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70945. for (var i = 0; i < gamepads.length; i++) {
  70946. var gamepad = gamepads[i];
  70947. if (gamepad) {
  70948. if (!this._babylonGamepads[gamepad.index]) {
  70949. var newGamepad = this._addNewGamepad(gamepad);
  70950. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70951. }
  70952. else {
  70953. // Forced to copy again this object for Chrome for unknown reason
  70954. this._babylonGamepads[i].browserGamepad = gamepad;
  70955. if (!this._babylonGamepads[i].isConnected) {
  70956. this._babylonGamepads[i]._isConnected = true;
  70957. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70958. }
  70959. }
  70960. }
  70961. }
  70962. };
  70963. return GamepadManager;
  70964. }());
  70965. BABYLON.GamepadManager = GamepadManager;
  70966. })(BABYLON || (BABYLON = {}));
  70967. //# sourceMappingURL=babylon.gamepadManager.js.map
  70968. var BABYLON;
  70969. (function (BABYLON) {
  70970. var StickValues = /** @class */ (function () {
  70971. function StickValues(x, y) {
  70972. this.x = x;
  70973. this.y = y;
  70974. }
  70975. return StickValues;
  70976. }());
  70977. BABYLON.StickValues = StickValues;
  70978. var Gamepad = /** @class */ (function () {
  70979. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70980. if (leftStickX === void 0) { leftStickX = 0; }
  70981. if (leftStickY === void 0) { leftStickY = 1; }
  70982. if (rightStickX === void 0) { rightStickX = 2; }
  70983. if (rightStickY === void 0) { rightStickY = 3; }
  70984. this.id = id;
  70985. this.index = index;
  70986. this.browserGamepad = browserGamepad;
  70987. this._isConnected = true;
  70988. this._invertLeftStickY = false;
  70989. this.type = Gamepad.GAMEPAD;
  70990. this._leftStickAxisX = leftStickX;
  70991. this._leftStickAxisY = leftStickY;
  70992. this._rightStickAxisX = rightStickX;
  70993. this._rightStickAxisY = rightStickY;
  70994. if (this.browserGamepad.axes.length >= 2) {
  70995. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70996. }
  70997. if (this.browserGamepad.axes.length >= 4) {
  70998. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70999. }
  71000. }
  71001. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71002. get: function () {
  71003. return this._isConnected;
  71004. },
  71005. enumerable: true,
  71006. configurable: true
  71007. });
  71008. Gamepad.prototype.onleftstickchanged = function (callback) {
  71009. this._onleftstickchanged = callback;
  71010. };
  71011. Gamepad.prototype.onrightstickchanged = function (callback) {
  71012. this._onrightstickchanged = callback;
  71013. };
  71014. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71015. get: function () {
  71016. return this._leftStick;
  71017. },
  71018. set: function (newValues) {
  71019. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71020. this._onleftstickchanged(newValues);
  71021. }
  71022. this._leftStick = newValues;
  71023. },
  71024. enumerable: true,
  71025. configurable: true
  71026. });
  71027. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71028. get: function () {
  71029. return this._rightStick;
  71030. },
  71031. set: function (newValues) {
  71032. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71033. this._onrightstickchanged(newValues);
  71034. }
  71035. this._rightStick = newValues;
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. Gamepad.prototype.update = function () {
  71041. if (this._leftStick) {
  71042. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71043. if (this._invertLeftStickY) {
  71044. this.leftStick.y *= -1;
  71045. }
  71046. }
  71047. if (this._rightStick) {
  71048. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71049. }
  71050. };
  71051. Gamepad.prototype.dispose = function () {
  71052. };
  71053. Gamepad.GAMEPAD = 0;
  71054. Gamepad.GENERIC = 1;
  71055. Gamepad.XBOX = 2;
  71056. Gamepad.POSE_ENABLED = 3;
  71057. return Gamepad;
  71058. }());
  71059. BABYLON.Gamepad = Gamepad;
  71060. var GenericPad = /** @class */ (function (_super) {
  71061. __extends(GenericPad, _super);
  71062. function GenericPad(id, index, browserGamepad) {
  71063. var _this = _super.call(this, id, index, browserGamepad) || this;
  71064. _this.onButtonDownObservable = new BABYLON.Observable();
  71065. _this.onButtonUpObservable = new BABYLON.Observable();
  71066. _this.type = Gamepad.GENERIC;
  71067. _this._buttons = new Array(browserGamepad.buttons.length);
  71068. return _this;
  71069. }
  71070. GenericPad.prototype.onbuttondown = function (callback) {
  71071. this._onbuttondown = callback;
  71072. };
  71073. GenericPad.prototype.onbuttonup = function (callback) {
  71074. this._onbuttonup = callback;
  71075. };
  71076. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71077. if (newValue !== currentValue) {
  71078. if (newValue === 1) {
  71079. if (this._onbuttondown) {
  71080. this._onbuttondown(buttonIndex);
  71081. }
  71082. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71083. }
  71084. if (newValue === 0) {
  71085. if (this._onbuttonup) {
  71086. this._onbuttonup(buttonIndex);
  71087. }
  71088. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71089. }
  71090. }
  71091. return newValue;
  71092. };
  71093. GenericPad.prototype.update = function () {
  71094. _super.prototype.update.call(this);
  71095. for (var index = 0; index < this._buttons.length; index++) {
  71096. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71097. }
  71098. };
  71099. GenericPad.prototype.dispose = function () {
  71100. _super.prototype.dispose.call(this);
  71101. this.onButtonDownObservable.clear();
  71102. this.onButtonUpObservable.clear();
  71103. };
  71104. return GenericPad;
  71105. }(Gamepad));
  71106. BABYLON.GenericPad = GenericPad;
  71107. })(BABYLON || (BABYLON = {}));
  71108. //# sourceMappingURL=babylon.gamepad.js.map
  71109. var BABYLON;
  71110. (function (BABYLON) {
  71111. /**
  71112. * Defines supported buttons for XBox360 compatible gamepads
  71113. */
  71114. var Xbox360Button;
  71115. (function (Xbox360Button) {
  71116. /** A */
  71117. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71118. /** B */
  71119. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71120. /** X */
  71121. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71122. /** Y */
  71123. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71124. /** Start */
  71125. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71126. /** Back */
  71127. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71128. /** Left button */
  71129. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71130. /** Right button */
  71131. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71132. /** Left stick */
  71133. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71134. /** Right stick */
  71135. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71136. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71137. /** Defines values for XBox360 DPad */
  71138. var Xbox360Dpad;
  71139. (function (Xbox360Dpad) {
  71140. /** Up */
  71141. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71142. /** Down */
  71143. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71144. /** Left */
  71145. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71146. /** Right */
  71147. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71148. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71149. /**
  71150. * Defines a XBox360 gamepad
  71151. */
  71152. var Xbox360Pad = /** @class */ (function (_super) {
  71153. __extends(Xbox360Pad, _super);
  71154. /**
  71155. * Creates a new XBox360 gamepad object
  71156. * @param id defines the id of this gamepad
  71157. * @param index defines its index
  71158. * @param gamepad defines the internal HTML gamepad object
  71159. * @param xboxOne defines if it is a XBox One gamepad
  71160. */
  71161. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71162. if (xboxOne === void 0) { xboxOne = false; }
  71163. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71164. _this._leftTrigger = 0;
  71165. _this._rightTrigger = 0;
  71166. /** Observable raised when a button is pressed */
  71167. _this.onButtonDownObservable = new BABYLON.Observable();
  71168. /** Observable raised when a button is released */
  71169. _this.onButtonUpObservable = new BABYLON.Observable();
  71170. /** Observable raised when a pad is pressed */
  71171. _this.onPadDownObservable = new BABYLON.Observable();
  71172. /** Observable raised when a pad is released */
  71173. _this.onPadUpObservable = new BABYLON.Observable();
  71174. _this._buttonA = 0;
  71175. _this._buttonB = 0;
  71176. _this._buttonX = 0;
  71177. _this._buttonY = 0;
  71178. _this._buttonBack = 0;
  71179. _this._buttonStart = 0;
  71180. _this._buttonLB = 0;
  71181. _this._buttonRB = 0;
  71182. _this._buttonLeftStick = 0;
  71183. _this._buttonRightStick = 0;
  71184. _this._dPadUp = 0;
  71185. _this._dPadDown = 0;
  71186. _this._dPadLeft = 0;
  71187. _this._dPadRight = 0;
  71188. _this._isXboxOnePad = false;
  71189. _this.type = BABYLON.Gamepad.XBOX;
  71190. _this._isXboxOnePad = xboxOne;
  71191. return _this;
  71192. }
  71193. /**
  71194. * Defines the callback to call when left trigger is pressed
  71195. * @param callback defines the callback to use
  71196. */
  71197. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71198. this._onlefttriggerchanged = callback;
  71199. };
  71200. /**
  71201. * Defines the callback to call when right trigger is pressed
  71202. * @param callback defines the callback to use
  71203. */
  71204. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71205. this._onrighttriggerchanged = callback;
  71206. };
  71207. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71208. /**
  71209. * Gets or sets left trigger value
  71210. */
  71211. get: function () {
  71212. return this._leftTrigger;
  71213. },
  71214. set: function (newValue) {
  71215. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71216. this._onlefttriggerchanged(newValue);
  71217. }
  71218. this._leftTrigger = newValue;
  71219. },
  71220. enumerable: true,
  71221. configurable: true
  71222. });
  71223. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71224. /**
  71225. * Gets or sets right trigger value
  71226. */
  71227. get: function () {
  71228. return this._rightTrigger;
  71229. },
  71230. set: function (newValue) {
  71231. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71232. this._onrighttriggerchanged(newValue);
  71233. }
  71234. this._rightTrigger = newValue;
  71235. },
  71236. enumerable: true,
  71237. configurable: true
  71238. });
  71239. /**
  71240. * Defines the callback to call when a button is pressed
  71241. * @param callback defines the callback to use
  71242. */
  71243. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71244. this._onbuttondown = callback;
  71245. };
  71246. /**
  71247. * Defines the callback to call when a button is released
  71248. * @param callback defines the callback to use
  71249. */
  71250. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71251. this._onbuttonup = callback;
  71252. };
  71253. /**
  71254. * Defines the callback to call when a pad is pressed
  71255. * @param callback defines the callback to use
  71256. */
  71257. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71258. this._ondpaddown = callback;
  71259. };
  71260. /**
  71261. * Defines the callback to call when a pad is released
  71262. * @param callback defines the callback to use
  71263. */
  71264. Xbox360Pad.prototype.ondpadup = function (callback) {
  71265. this._ondpadup = callback;
  71266. };
  71267. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71268. if (newValue !== currentValue) {
  71269. if (newValue === 1) {
  71270. if (this._onbuttondown) {
  71271. this._onbuttondown(buttonType);
  71272. }
  71273. this.onButtonDownObservable.notifyObservers(buttonType);
  71274. }
  71275. if (newValue === 0) {
  71276. if (this._onbuttonup) {
  71277. this._onbuttonup(buttonType);
  71278. }
  71279. this.onButtonUpObservable.notifyObservers(buttonType);
  71280. }
  71281. }
  71282. return newValue;
  71283. };
  71284. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71285. if (newValue !== currentValue) {
  71286. if (newValue === 1) {
  71287. if (this._ondpaddown) {
  71288. this._ondpaddown(buttonType);
  71289. }
  71290. this.onPadDownObservable.notifyObservers(buttonType);
  71291. }
  71292. if (newValue === 0) {
  71293. if (this._ondpadup) {
  71294. this._ondpadup(buttonType);
  71295. }
  71296. this.onPadUpObservable.notifyObservers(buttonType);
  71297. }
  71298. }
  71299. return newValue;
  71300. };
  71301. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71302. /** Gets or sets value of A button */
  71303. get: function () {
  71304. return this._buttonA;
  71305. },
  71306. set: function (value) {
  71307. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71308. },
  71309. enumerable: true,
  71310. configurable: true
  71311. });
  71312. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71313. /** Gets or sets value of B button */
  71314. get: function () {
  71315. return this._buttonB;
  71316. },
  71317. set: function (value) {
  71318. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71319. },
  71320. enumerable: true,
  71321. configurable: true
  71322. });
  71323. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71324. /** Gets or sets value of X button */
  71325. get: function () {
  71326. return this._buttonX;
  71327. },
  71328. set: function (value) {
  71329. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71330. },
  71331. enumerable: true,
  71332. configurable: true
  71333. });
  71334. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71335. /** Gets or sets value of Y button */
  71336. get: function () {
  71337. return this._buttonY;
  71338. },
  71339. set: function (value) {
  71340. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71341. },
  71342. enumerable: true,
  71343. configurable: true
  71344. });
  71345. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71346. /** Gets or sets value of Start button */
  71347. get: function () {
  71348. return this._buttonStart;
  71349. },
  71350. set: function (value) {
  71351. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71352. },
  71353. enumerable: true,
  71354. configurable: true
  71355. });
  71356. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71357. /** Gets or sets value of Back button */
  71358. get: function () {
  71359. return this._buttonBack;
  71360. },
  71361. set: function (value) {
  71362. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71363. },
  71364. enumerable: true,
  71365. configurable: true
  71366. });
  71367. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71368. /** Gets or sets value of Left button */
  71369. get: function () {
  71370. return this._buttonLB;
  71371. },
  71372. set: function (value) {
  71373. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71374. },
  71375. enumerable: true,
  71376. configurable: true
  71377. });
  71378. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71379. /** Gets or sets value of Right button */
  71380. get: function () {
  71381. return this._buttonRB;
  71382. },
  71383. set: function (value) {
  71384. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71385. },
  71386. enumerable: true,
  71387. configurable: true
  71388. });
  71389. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71390. /** Gets or sets value of left stick */
  71391. get: function () {
  71392. return this._buttonLeftStick;
  71393. },
  71394. set: function (value) {
  71395. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71401. /** Gets or sets value of right stick */
  71402. get: function () {
  71403. return this._buttonRightStick;
  71404. },
  71405. set: function (value) {
  71406. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71407. },
  71408. enumerable: true,
  71409. configurable: true
  71410. });
  71411. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71412. /** Gets or sets value of DPad up */
  71413. get: function () {
  71414. return this._dPadUp;
  71415. },
  71416. set: function (value) {
  71417. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71418. },
  71419. enumerable: true,
  71420. configurable: true
  71421. });
  71422. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71423. /** Gets or sets value of DPad down */
  71424. get: function () {
  71425. return this._dPadDown;
  71426. },
  71427. set: function (value) {
  71428. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71429. },
  71430. enumerable: true,
  71431. configurable: true
  71432. });
  71433. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71434. /** Gets or sets value of DPad left */
  71435. get: function () {
  71436. return this._dPadLeft;
  71437. },
  71438. set: function (value) {
  71439. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71440. },
  71441. enumerable: true,
  71442. configurable: true
  71443. });
  71444. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71445. /** Gets or sets value of DPad right */
  71446. get: function () {
  71447. return this._dPadRight;
  71448. },
  71449. set: function (value) {
  71450. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71451. },
  71452. enumerable: true,
  71453. configurable: true
  71454. });
  71455. /**
  71456. * Force the gamepad to synchronize with device values
  71457. */
  71458. Xbox360Pad.prototype.update = function () {
  71459. _super.prototype.update.call(this);
  71460. if (this._isXboxOnePad) {
  71461. this.buttonA = this.browserGamepad.buttons[0].value;
  71462. this.buttonB = this.browserGamepad.buttons[1].value;
  71463. this.buttonX = this.browserGamepad.buttons[2].value;
  71464. this.buttonY = this.browserGamepad.buttons[3].value;
  71465. this.buttonLB = this.browserGamepad.buttons[4].value;
  71466. this.buttonRB = this.browserGamepad.buttons[5].value;
  71467. this.leftTrigger = this.browserGamepad.axes[2];
  71468. this.rightTrigger = this.browserGamepad.axes[5];
  71469. this.buttonBack = this.browserGamepad.buttons[9].value;
  71470. this.buttonStart = this.browserGamepad.buttons[8].value;
  71471. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71472. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71473. this.dPadUp = this.browserGamepad.buttons[11].value;
  71474. this.dPadDown = this.browserGamepad.buttons[12].value;
  71475. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71476. this.dPadRight = this.browserGamepad.buttons[14].value;
  71477. }
  71478. else {
  71479. this.buttonA = this.browserGamepad.buttons[0].value;
  71480. this.buttonB = this.browserGamepad.buttons[1].value;
  71481. this.buttonX = this.browserGamepad.buttons[2].value;
  71482. this.buttonY = this.browserGamepad.buttons[3].value;
  71483. this.buttonLB = this.browserGamepad.buttons[4].value;
  71484. this.buttonRB = this.browserGamepad.buttons[5].value;
  71485. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71486. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71487. this.buttonBack = this.browserGamepad.buttons[8].value;
  71488. this.buttonStart = this.browserGamepad.buttons[9].value;
  71489. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71490. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71491. this.dPadUp = this.browserGamepad.buttons[12].value;
  71492. this.dPadDown = this.browserGamepad.buttons[13].value;
  71493. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71494. this.dPadRight = this.browserGamepad.buttons[15].value;
  71495. }
  71496. };
  71497. Xbox360Pad.prototype.dispose = function () {
  71498. _super.prototype.dispose.call(this);
  71499. this.onButtonDownObservable.clear();
  71500. this.onButtonUpObservable.clear();
  71501. this.onPadDownObservable.clear();
  71502. this.onPadUpObservable.clear();
  71503. };
  71504. return Xbox360Pad;
  71505. }(BABYLON.Gamepad));
  71506. BABYLON.Xbox360Pad = Xbox360Pad;
  71507. })(BABYLON || (BABYLON = {}));
  71508. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71509. var BABYLON;
  71510. (function (BABYLON) {
  71511. /**
  71512. * Defines the types of pose enabled controllers that are supported
  71513. */
  71514. var PoseEnabledControllerType;
  71515. (function (PoseEnabledControllerType) {
  71516. /**
  71517. * HTC Vive
  71518. */
  71519. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71520. /**
  71521. * Oculus Rift
  71522. */
  71523. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71524. /**
  71525. * Windows mixed reality
  71526. */
  71527. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71528. /**
  71529. * Samsung gear VR
  71530. */
  71531. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71532. /**
  71533. * Google Daydream
  71534. */
  71535. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71536. /**
  71537. * Generic
  71538. */
  71539. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71540. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71541. /**
  71542. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71543. */
  71544. var PoseEnabledControllerHelper = /** @class */ (function () {
  71545. function PoseEnabledControllerHelper() {
  71546. }
  71547. /**
  71548. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71549. * @param vrGamepad the gamepad to initialized
  71550. * @returns a vr controller of the type the gamepad identified as
  71551. */
  71552. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71553. // Oculus Touch
  71554. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71555. return new BABYLON.OculusTouchController(vrGamepad);
  71556. }
  71557. // Windows Mixed Reality controllers
  71558. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71559. return new BABYLON.WindowsMotionController(vrGamepad);
  71560. }
  71561. // HTC Vive
  71562. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71563. return new BABYLON.ViveController(vrGamepad);
  71564. }
  71565. // Samsung/Oculus Gear VR or Oculus Go
  71566. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71567. return new BABYLON.GearVRController(vrGamepad);
  71568. }
  71569. // Google Daydream
  71570. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71571. return new BABYLON.DaydreamController(vrGamepad);
  71572. }
  71573. // Generic
  71574. else {
  71575. return new BABYLON.GenericController(vrGamepad);
  71576. }
  71577. };
  71578. return PoseEnabledControllerHelper;
  71579. }());
  71580. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71581. /**
  71582. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71583. */
  71584. var PoseEnabledController = /** @class */ (function (_super) {
  71585. __extends(PoseEnabledController, _super);
  71586. /**
  71587. * Creates a new PoseEnabledController from a gamepad
  71588. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71589. */
  71590. function PoseEnabledController(browserGamepad) {
  71591. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71592. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71593. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71594. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71595. /**
  71596. * The device position in babylon space
  71597. */
  71598. _this.devicePosition = BABYLON.Vector3.Zero();
  71599. /**
  71600. * The device rotation in babylon space
  71601. */
  71602. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71603. /**
  71604. * The scale factor of the device in babylon space
  71605. */
  71606. _this.deviceScaleFactor = 1;
  71607. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71608. /**
  71609. * Internal, matrix used to convert room space to babylon space
  71610. */
  71611. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71612. /**
  71613. * Node to be used when casting a ray from the controller
  71614. */
  71615. _this._pointingPoseNode = null;
  71616. _this._workingMatrix = BABYLON.Matrix.Identity();
  71617. /**
  71618. * @hidden
  71619. */
  71620. _this._meshAttachedObservable = new BABYLON.Observable();
  71621. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71622. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71623. _this.position = BABYLON.Vector3.Zero();
  71624. _this.rotationQuaternion = new BABYLON.Quaternion();
  71625. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71626. _this._calculatedRotation = new BABYLON.Quaternion();
  71627. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71628. return _this;
  71629. }
  71630. /**
  71631. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71632. */
  71633. PoseEnabledController.prototype.update = function () {
  71634. _super.prototype.update.call(this);
  71635. this._updatePoseAndMesh();
  71636. };
  71637. /**
  71638. * Updates only the pose device and mesh without doing any button event checking
  71639. */
  71640. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71641. var pose = this.browserGamepad.pose;
  71642. this.updateFromDevice(pose);
  71643. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71644. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71645. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71646. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71647. if (this._mesh) {
  71648. this._mesh.position.copyFrom(this.devicePosition);
  71649. if (this._mesh.rotationQuaternion) {
  71650. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71651. }
  71652. }
  71653. };
  71654. /**
  71655. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71656. * @param poseData raw pose fromthe device
  71657. */
  71658. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71659. if (poseData) {
  71660. this.rawPose = poseData;
  71661. if (poseData.position) {
  71662. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71663. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71664. this._deviceRoomPosition.z *= -1;
  71665. }
  71666. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71667. this._calculatedPosition.addInPlace(this.position);
  71668. }
  71669. var pose = this.rawPose;
  71670. if (poseData.orientation && pose.orientation) {
  71671. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71672. if (this._mesh) {
  71673. if (this._mesh.getScene().useRightHandedSystem) {
  71674. this._deviceRoomRotationQuaternion.z *= -1;
  71675. this._deviceRoomRotationQuaternion.w *= -1;
  71676. }
  71677. else {
  71678. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71679. }
  71680. }
  71681. // if the camera is set, rotate to the camera's rotation
  71682. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71683. }
  71684. }
  71685. };
  71686. /**
  71687. * Attaches a mesh to the controller
  71688. * @param mesh the mesh to be attached
  71689. */
  71690. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71691. if (this._mesh) {
  71692. this._mesh.parent = null;
  71693. }
  71694. this._mesh = mesh;
  71695. if (this._poseControlledCamera) {
  71696. this._mesh.parent = this._poseControlledCamera;
  71697. }
  71698. if (!this._mesh.rotationQuaternion) {
  71699. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71700. }
  71701. // 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
  71702. this._updatePoseAndMesh();
  71703. if (this._pointingPoseNode) {
  71704. var parents = [];
  71705. var obj = this._pointingPoseNode;
  71706. while (obj.parent) {
  71707. parents.push(obj.parent);
  71708. obj = obj.parent;
  71709. }
  71710. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71711. }
  71712. this._meshAttachedObservable.notifyObservers(mesh);
  71713. };
  71714. /**
  71715. * Attaches the controllers mesh to a camera
  71716. * @param camera the camera the mesh should be attached to
  71717. */
  71718. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71719. this._poseControlledCamera = camera;
  71720. if (this._mesh) {
  71721. this._mesh.parent = this._poseControlledCamera;
  71722. }
  71723. };
  71724. /**
  71725. * Disposes of the controller
  71726. */
  71727. PoseEnabledController.prototype.dispose = function () {
  71728. if (this._mesh) {
  71729. this._mesh.dispose();
  71730. }
  71731. this._mesh = null;
  71732. _super.prototype.dispose.call(this);
  71733. };
  71734. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71735. /**
  71736. * The mesh that is attached to the controller
  71737. */
  71738. get: function () {
  71739. return this._mesh;
  71740. },
  71741. enumerable: true,
  71742. configurable: true
  71743. });
  71744. /**
  71745. * Gets the ray of the controller in the direction the controller is pointing
  71746. * @param length the length the resulting ray should be
  71747. * @returns a ray in the direction the controller is pointing
  71748. */
  71749. PoseEnabledController.prototype.getForwardRay = function (length) {
  71750. if (length === void 0) { length = 100; }
  71751. if (!this.mesh) {
  71752. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71753. }
  71754. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71755. var origin = m.getTranslation();
  71756. var forward = new BABYLON.Vector3(0, 0, -1);
  71757. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71758. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71759. return new BABYLON.Ray(origin, direction, length);
  71760. };
  71761. /**
  71762. * Name of the child mesh that can be used to cast a ray from the controller
  71763. */
  71764. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71765. return PoseEnabledController;
  71766. }(BABYLON.Gamepad));
  71767. BABYLON.PoseEnabledController = PoseEnabledController;
  71768. })(BABYLON || (BABYLON = {}));
  71769. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71770. var BABYLON;
  71771. (function (BABYLON) {
  71772. /**
  71773. * Defines the WebVRController object that represents controllers tracked in 3D space
  71774. */
  71775. var WebVRController = /** @class */ (function (_super) {
  71776. __extends(WebVRController, _super);
  71777. /**
  71778. * Creates a new WebVRController from a gamepad
  71779. * @param vrGamepad the gamepad that the WebVRController should be created from
  71780. */
  71781. function WebVRController(vrGamepad) {
  71782. var _this = _super.call(this, vrGamepad) || this;
  71783. // Observables
  71784. /**
  71785. * Fired when the trigger state has changed
  71786. */
  71787. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71788. /**
  71789. * Fired when the main button state has changed
  71790. */
  71791. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71792. /**
  71793. * Fired when the secondary button state has changed
  71794. */
  71795. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71796. /**
  71797. * Fired when the pad state has changed
  71798. */
  71799. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71800. /**
  71801. * Fired when controllers stick values have changed
  71802. */
  71803. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71804. /**
  71805. * X and Y axis corrisponding to the controllers joystick
  71806. */
  71807. _this.pad = { x: 0, y: 0 };
  71808. // avoid GC, store state in a tmp object
  71809. _this._changes = {
  71810. pressChanged: false,
  71811. touchChanged: false,
  71812. valueChanged: false,
  71813. changed: false
  71814. };
  71815. _this._buttons = new Array(vrGamepad.buttons.length);
  71816. _this.hand = vrGamepad.hand;
  71817. return _this;
  71818. }
  71819. /**
  71820. * Fired when a controller button's state has changed
  71821. * @param callback the callback containing the button that was modified
  71822. */
  71823. WebVRController.prototype.onButtonStateChange = function (callback) {
  71824. this._onButtonStateChange = callback;
  71825. };
  71826. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71827. /**
  71828. * The default controller model for the controller
  71829. */
  71830. get: function () {
  71831. return this._defaultModel;
  71832. },
  71833. enumerable: true,
  71834. configurable: true
  71835. });
  71836. /**
  71837. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71838. */
  71839. WebVRController.prototype.update = function () {
  71840. _super.prototype.update.call(this);
  71841. for (var index = 0; index < this._buttons.length; index++) {
  71842. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71843. }
  71844. ;
  71845. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71846. this.pad.x = this.leftStick.x;
  71847. this.pad.y = this.leftStick.y;
  71848. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71849. }
  71850. };
  71851. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71852. if (!newState) {
  71853. newState = {
  71854. pressed: false,
  71855. touched: false,
  71856. value: 0
  71857. };
  71858. }
  71859. if (!currentState) {
  71860. this._buttons[buttonIndex] = {
  71861. pressed: newState.pressed,
  71862. touched: newState.touched,
  71863. value: newState.value
  71864. };
  71865. return;
  71866. }
  71867. this._checkChanges(newState, currentState);
  71868. if (this._changes.changed) {
  71869. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71870. this._handleButtonChange(buttonIndex, newState, this._changes);
  71871. }
  71872. this._buttons[buttonIndex].pressed = newState.pressed;
  71873. this._buttons[buttonIndex].touched = newState.touched;
  71874. // oculus triggers are never 0, thou not touched.
  71875. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71876. };
  71877. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71878. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71879. this._changes.touchChanged = newState.touched !== currentState.touched;
  71880. this._changes.valueChanged = newState.value !== currentState.value;
  71881. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71882. return this._changes;
  71883. };
  71884. /**
  71885. * Disposes of th webVRCOntroller
  71886. */
  71887. WebVRController.prototype.dispose = function () {
  71888. _super.prototype.dispose.call(this);
  71889. this.onTriggerStateChangedObservable.clear();
  71890. this.onMainButtonStateChangedObservable.clear();
  71891. this.onSecondaryButtonStateChangedObservable.clear();
  71892. this.onPadStateChangedObservable.clear();
  71893. this.onPadValuesChangedObservable.clear();
  71894. };
  71895. return WebVRController;
  71896. }(BABYLON.PoseEnabledController));
  71897. BABYLON.WebVRController = WebVRController;
  71898. })(BABYLON || (BABYLON = {}));
  71899. //# sourceMappingURL=babylon.webVRController.js.map
  71900. var BABYLON;
  71901. (function (BABYLON) {
  71902. /**
  71903. * Oculus Touch Controller
  71904. */
  71905. var OculusTouchController = /** @class */ (function (_super) {
  71906. __extends(OculusTouchController, _super);
  71907. /**
  71908. * Creates a new OculusTouchController from a gamepad
  71909. * @param vrGamepad the gamepad that the controller should be created from
  71910. */
  71911. function OculusTouchController(vrGamepad) {
  71912. var _this = _super.call(this, vrGamepad) || this;
  71913. /**
  71914. * Fired when the secondary trigger on this controller is modified
  71915. */
  71916. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71917. /**
  71918. * Fired when the thumb rest on this controller is modified
  71919. */
  71920. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71921. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71922. return _this;
  71923. }
  71924. /**
  71925. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71926. * @param scene scene in which to add meshes
  71927. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71928. */
  71929. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71930. var _this = this;
  71931. var meshName;
  71932. // Hand
  71933. if (this.hand === 'left') {
  71934. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71935. }
  71936. else { // Right is the default if no hand is specified
  71937. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71938. }
  71939. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71940. /*
  71941. Parent Mesh name: oculus_touch_left
  71942. - body
  71943. - trigger
  71944. - thumbstick
  71945. - grip
  71946. - button_y
  71947. - button_x
  71948. - button_enter
  71949. */
  71950. _this._defaultModel = newMeshes[1];
  71951. _this.attachToMesh(_this._defaultModel);
  71952. if (meshLoaded) {
  71953. meshLoaded(_this._defaultModel);
  71954. }
  71955. });
  71956. };
  71957. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71958. /**
  71959. * Fired when the A button on this controller is modified
  71960. */
  71961. get: function () {
  71962. if (this.hand === 'right') {
  71963. return this.onMainButtonStateChangedObservable;
  71964. }
  71965. else {
  71966. throw new Error('No A button on left hand');
  71967. }
  71968. },
  71969. enumerable: true,
  71970. configurable: true
  71971. });
  71972. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71973. /**
  71974. * Fired when the B button on this controller is modified
  71975. */
  71976. get: function () {
  71977. if (this.hand === 'right') {
  71978. return this.onSecondaryButtonStateChangedObservable;
  71979. }
  71980. else {
  71981. throw new Error('No B button on left hand');
  71982. }
  71983. },
  71984. enumerable: true,
  71985. configurable: true
  71986. });
  71987. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71988. /**
  71989. * Fired when the X button on this controller is modified
  71990. */
  71991. get: function () {
  71992. if (this.hand === 'left') {
  71993. return this.onMainButtonStateChangedObservable;
  71994. }
  71995. else {
  71996. throw new Error('No X button on right hand');
  71997. }
  71998. },
  71999. enumerable: true,
  72000. configurable: true
  72001. });
  72002. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72003. /**
  72004. * Fired when the Y button on this controller is modified
  72005. */
  72006. get: function () {
  72007. if (this.hand === 'left') {
  72008. return this.onSecondaryButtonStateChangedObservable;
  72009. }
  72010. else {
  72011. throw new Error('No Y button on right hand');
  72012. }
  72013. },
  72014. enumerable: true,
  72015. configurable: true
  72016. });
  72017. /**
  72018. * Called once for each button that changed state since the last frame
  72019. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72020. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72021. * 2) secondary trigger (same)
  72022. * 3) A (right) X (left), touch, pressed = value
  72023. * 4) B / Y
  72024. * 5) thumb rest
  72025. * @param buttonIdx Which button index changed
  72026. * @param state New state of the button
  72027. * @param changes Which properties on the state changed since last frame
  72028. */
  72029. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72030. var notifyObject = state; //{ state: state, changes: changes };
  72031. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72032. switch (buttonIdx) {
  72033. case 0:
  72034. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72035. return;
  72036. case 1: // index trigger
  72037. if (this._defaultModel) {
  72038. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72039. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72040. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72041. }
  72042. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72043. return;
  72044. case 2: // secondary trigger
  72045. if (this._defaultModel) {
  72046. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72047. }
  72048. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72049. return;
  72050. case 3:
  72051. if (this._defaultModel) {
  72052. if (notifyObject.pressed) {
  72053. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72054. }
  72055. else {
  72056. (this._defaultModel.getChildren()[1]).position.y = 0;
  72057. }
  72058. }
  72059. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72060. return;
  72061. case 4:
  72062. if (this._defaultModel) {
  72063. if (notifyObject.pressed) {
  72064. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72065. }
  72066. else {
  72067. (this._defaultModel.getChildren()[2]).position.y = 0;
  72068. }
  72069. }
  72070. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72071. return;
  72072. case 5:
  72073. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72074. return;
  72075. }
  72076. };
  72077. /**
  72078. * Base Url for the controller model.
  72079. */
  72080. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72081. /**
  72082. * File name for the left controller model.
  72083. */
  72084. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72085. /**
  72086. * File name for the right controller model.
  72087. */
  72088. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72089. return OculusTouchController;
  72090. }(BABYLON.WebVRController));
  72091. BABYLON.OculusTouchController = OculusTouchController;
  72092. })(BABYLON || (BABYLON = {}));
  72093. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72094. var BABYLON;
  72095. (function (BABYLON) {
  72096. /**
  72097. * Vive Controller
  72098. */
  72099. var ViveController = /** @class */ (function (_super) {
  72100. __extends(ViveController, _super);
  72101. /**
  72102. * Creates a new ViveController from a gamepad
  72103. * @param vrGamepad the gamepad that the controller should be created from
  72104. */
  72105. function ViveController(vrGamepad) {
  72106. var _this = _super.call(this, vrGamepad) || this;
  72107. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72108. _this._invertLeftStickY = true;
  72109. return _this;
  72110. }
  72111. /**
  72112. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72113. * @param scene scene in which to add meshes
  72114. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72115. */
  72116. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72117. var _this = this;
  72118. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72119. /*
  72120. Parent Mesh name: ViveWand
  72121. - body
  72122. - r_gripper
  72123. - l_gripper
  72124. - menu_button
  72125. - system_button
  72126. - trackpad
  72127. - trigger
  72128. - LED
  72129. */
  72130. _this._defaultModel = newMeshes[1];
  72131. _this.attachToMesh(_this._defaultModel);
  72132. if (meshLoaded) {
  72133. meshLoaded(_this._defaultModel);
  72134. }
  72135. });
  72136. };
  72137. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72138. /**
  72139. * Fired when the left button on this controller is modified
  72140. */
  72141. get: function () {
  72142. return this.onMainButtonStateChangedObservable;
  72143. },
  72144. enumerable: true,
  72145. configurable: true
  72146. });
  72147. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72148. /**
  72149. * Fired when the right button on this controller is modified
  72150. */
  72151. get: function () {
  72152. return this.onMainButtonStateChangedObservable;
  72153. },
  72154. enumerable: true,
  72155. configurable: true
  72156. });
  72157. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72158. /**
  72159. * Fired when the menu button on this controller is modified
  72160. */
  72161. get: function () {
  72162. return this.onSecondaryButtonStateChangedObservable;
  72163. },
  72164. enumerable: true,
  72165. configurable: true
  72166. });
  72167. /**
  72168. * Called once for each button that changed state since the last frame
  72169. * Vive mapping:
  72170. * 0: touchpad
  72171. * 1: trigger
  72172. * 2: left AND right buttons
  72173. * 3: menu button
  72174. * @param buttonIdx Which button index changed
  72175. * @param state New state of the button
  72176. * @param changes Which properties on the state changed since last frame
  72177. */
  72178. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72179. var notifyObject = state; //{ state: state, changes: changes };
  72180. switch (buttonIdx) {
  72181. case 0:
  72182. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72183. return;
  72184. case 1: // index trigger
  72185. if (this._defaultModel) {
  72186. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72187. }
  72188. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72189. return;
  72190. case 2: // left AND right button
  72191. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72192. return;
  72193. case 3:
  72194. if (this._defaultModel) {
  72195. if (notifyObject.pressed) {
  72196. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72197. }
  72198. else {
  72199. (this._defaultModel.getChildren()[2]).position.y = 0;
  72200. }
  72201. }
  72202. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72203. return;
  72204. }
  72205. };
  72206. /**
  72207. * Base Url for the controller model.
  72208. */
  72209. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72210. /**
  72211. * File name for the controller model.
  72212. */
  72213. ViveController.MODEL_FILENAME = 'wand.babylon';
  72214. return ViveController;
  72215. }(BABYLON.WebVRController));
  72216. BABYLON.ViveController = ViveController;
  72217. })(BABYLON || (BABYLON = {}));
  72218. //# sourceMappingURL=babylon.viveController.js.map
  72219. var BABYLON;
  72220. (function (BABYLON) {
  72221. /**
  72222. * Generic Controller
  72223. */
  72224. var GenericController = /** @class */ (function (_super) {
  72225. __extends(GenericController, _super);
  72226. /**
  72227. * Creates a new GenericController from a gamepad
  72228. * @param vrGamepad the gamepad that the controller should be created from
  72229. */
  72230. function GenericController(vrGamepad) {
  72231. return _super.call(this, vrGamepad) || this;
  72232. }
  72233. /**
  72234. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72235. * @param scene scene in which to add meshes
  72236. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72237. */
  72238. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72239. var _this = this;
  72240. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72241. _this._defaultModel = newMeshes[1];
  72242. _this.attachToMesh(_this._defaultModel);
  72243. if (meshLoaded) {
  72244. meshLoaded(_this._defaultModel);
  72245. }
  72246. });
  72247. };
  72248. /**
  72249. * Called once for each button that changed state since the last frame
  72250. * @param buttonIdx Which button index changed
  72251. * @param state New state of the button
  72252. * @param changes Which properties on the state changed since last frame
  72253. */
  72254. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72255. console.log("Button id: " + buttonIdx + "state: ");
  72256. console.dir(state);
  72257. };
  72258. /**
  72259. * Base Url for the controller model.
  72260. */
  72261. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72262. /**
  72263. * File name for the controller model.
  72264. */
  72265. GenericController.MODEL_FILENAME = 'generic.babylon';
  72266. return GenericController;
  72267. }(BABYLON.WebVRController));
  72268. BABYLON.GenericController = GenericController;
  72269. })(BABYLON || (BABYLON = {}));
  72270. //# sourceMappingURL=babylon.genericController.js.map
  72271. var BABYLON;
  72272. (function (BABYLON) {
  72273. /**
  72274. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72275. */
  72276. var LoadedMeshInfo = /** @class */ (function () {
  72277. function LoadedMeshInfo() {
  72278. /**
  72279. * Map of the button meshes contained in the controller
  72280. */
  72281. this.buttonMeshes = {};
  72282. /**
  72283. * Map of the axis meshes contained in the controller
  72284. */
  72285. this.axisMeshes = {};
  72286. }
  72287. return LoadedMeshInfo;
  72288. }());
  72289. /**
  72290. * Defines the WindowsMotionController object that the state of the windows motion controller
  72291. */
  72292. var WindowsMotionController = /** @class */ (function (_super) {
  72293. __extends(WindowsMotionController, _super);
  72294. /**
  72295. * Creates a new WindowsMotionController from a gamepad
  72296. * @param vrGamepad the gamepad that the controller should be created from
  72297. */
  72298. function WindowsMotionController(vrGamepad) {
  72299. var _this = _super.call(this, vrGamepad) || this;
  72300. _this._mapping = {
  72301. // Semantic button names
  72302. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72303. // A mapping of the button name to glTF model node name
  72304. // that should be transformed by button value.
  72305. buttonMeshNames: {
  72306. 'trigger': 'SELECT',
  72307. 'menu': 'MENU',
  72308. 'grip': 'GRASP',
  72309. 'thumbstick': 'THUMBSTICK_PRESS',
  72310. 'trackpad': 'TOUCHPAD_PRESS'
  72311. },
  72312. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72313. buttonObservableNames: {
  72314. 'trigger': 'onTriggerStateChangedObservable',
  72315. 'menu': 'onSecondaryButtonStateChangedObservable',
  72316. 'grip': 'onMainButtonStateChangedObservable',
  72317. 'thumbstick': 'onPadStateChangedObservable',
  72318. 'trackpad': 'onTrackpadChangedObservable'
  72319. },
  72320. // A mapping of the axis name to glTF model node name
  72321. // that should be transformed by axis value.
  72322. // This array mirrors the browserGamepad.axes array, such that
  72323. // the mesh corresponding to axis 0 is in this array index 0.
  72324. axisMeshNames: [
  72325. 'THUMBSTICK_X',
  72326. 'THUMBSTICK_Y',
  72327. 'TOUCHPAD_TOUCH_X',
  72328. 'TOUCHPAD_TOUCH_Y'
  72329. ],
  72330. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72331. };
  72332. /**
  72333. * Fired when the trackpad on this controller is clicked
  72334. */
  72335. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72336. /**
  72337. * Fired when the trackpad on this controller is modified
  72338. */
  72339. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72340. /**
  72341. * The current x and y values of this controller's trackpad
  72342. */
  72343. _this.trackpad = { x: 0, y: 0 };
  72344. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72345. _this._loadedMeshInfo = null;
  72346. return _this;
  72347. }
  72348. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72349. /**
  72350. * Fired when the trigger on this controller is modified
  72351. */
  72352. get: function () {
  72353. return this.onTriggerStateChangedObservable;
  72354. },
  72355. enumerable: true,
  72356. configurable: true
  72357. });
  72358. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72359. /**
  72360. * Fired when the menu button on this controller is modified
  72361. */
  72362. get: function () {
  72363. return this.onSecondaryButtonStateChangedObservable;
  72364. },
  72365. enumerable: true,
  72366. configurable: true
  72367. });
  72368. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72369. /**
  72370. * Fired when the grip button on this controller is modified
  72371. */
  72372. get: function () {
  72373. return this.onMainButtonStateChangedObservable;
  72374. },
  72375. enumerable: true,
  72376. configurable: true
  72377. });
  72378. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72379. /**
  72380. * Fired when the thumbstick button on this controller is modified
  72381. */
  72382. get: function () {
  72383. return this.onPadStateChangedObservable;
  72384. },
  72385. enumerable: true,
  72386. configurable: true
  72387. });
  72388. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72389. /**
  72390. * Fired when the touchpad button on this controller is modified
  72391. */
  72392. get: function () {
  72393. return this.onTrackpadChangedObservable;
  72394. },
  72395. enumerable: true,
  72396. configurable: true
  72397. });
  72398. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72399. /**
  72400. * Fired when the touchpad values on this controller are modified
  72401. */
  72402. get: function () {
  72403. return this.onTrackpadValuesChangedObservable;
  72404. },
  72405. enumerable: true,
  72406. configurable: true
  72407. });
  72408. WindowsMotionController.prototype._updateTrackpad = function () {
  72409. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72410. this.trackpad.x = this.browserGamepad["axes"][2];
  72411. this.trackpad.y = this.browserGamepad["axes"][3];
  72412. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72413. }
  72414. };
  72415. /**
  72416. * Called once per frame by the engine.
  72417. */
  72418. WindowsMotionController.prototype.update = function () {
  72419. _super.prototype.update.call(this);
  72420. if (this.browserGamepad.axes) {
  72421. this._updateTrackpad();
  72422. // Only need to animate axes if there is a loaded mesh
  72423. if (this._loadedMeshInfo) {
  72424. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72425. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72426. }
  72427. }
  72428. }
  72429. };
  72430. /**
  72431. * Called once for each button that changed state since the last frame
  72432. * @param buttonIdx Which button index changed
  72433. * @param state New state of the button
  72434. * @param changes Which properties on the state changed since last frame
  72435. */
  72436. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72437. var buttonName = this._mapping.buttons[buttonIdx];
  72438. if (!buttonName) {
  72439. return;
  72440. }
  72441. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72442. this._updateTrackpad();
  72443. // Only emit events for buttons that we know how to map from index to name
  72444. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72445. if (observable) {
  72446. observable.notifyObservers(state);
  72447. }
  72448. this._lerpButtonTransform(buttonName, state.value);
  72449. };
  72450. /**
  72451. * Moves the buttons on the controller mesh based on their current state
  72452. * @param buttonName the name of the button to move
  72453. * @param buttonValue the value of the button which determines the buttons new position
  72454. */
  72455. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72456. // If there is no loaded mesh, there is nothing to transform.
  72457. if (!this._loadedMeshInfo) {
  72458. return;
  72459. }
  72460. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72461. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72462. return;
  72463. }
  72464. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72465. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72466. };
  72467. /**
  72468. * Moves the axis on the controller mesh based on its current state
  72469. * @param axis the index of the axis
  72470. * @param axisValue the value of the axis which determines the meshes new position
  72471. * @hidden
  72472. */
  72473. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72474. if (!this._loadedMeshInfo) {
  72475. return;
  72476. }
  72477. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72478. if (!meshInfo) {
  72479. return;
  72480. }
  72481. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72482. return;
  72483. }
  72484. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72485. var lerpValue = axisValue * 0.5 + 0.5;
  72486. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72487. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72488. };
  72489. /**
  72490. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72491. * @param scene scene in which to add meshes
  72492. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72493. */
  72494. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72495. var _this = this;
  72496. if (forceDefault === void 0) { forceDefault = false; }
  72497. var path;
  72498. var filename;
  72499. // Checking if GLB loader is present
  72500. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72501. // Determine the device specific folder based on the ID suffix
  72502. var device = 'default';
  72503. if (this.id && !forceDefault) {
  72504. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72505. device = ((match && match[0]) || device);
  72506. }
  72507. // Hand
  72508. if (this.hand === 'left') {
  72509. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72510. }
  72511. else { // Right is the default if no hand is specified
  72512. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72513. }
  72514. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72515. }
  72516. else {
  72517. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72518. path = BABYLON.GenericController.MODEL_BASE_URL;
  72519. filename = BABYLON.GenericController.MODEL_FILENAME;
  72520. }
  72521. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72522. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72523. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72524. if (!_this._loadedMeshInfo) {
  72525. return;
  72526. }
  72527. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72528. _this.attachToMesh(_this._defaultModel);
  72529. if (meshLoaded) {
  72530. meshLoaded(_this._defaultModel);
  72531. }
  72532. }, null, function (scene, message) {
  72533. BABYLON.Tools.Log(message);
  72534. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72535. if (!forceDefault) {
  72536. _this.initControllerMesh(scene, meshLoaded, true);
  72537. }
  72538. });
  72539. };
  72540. /**
  72541. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72542. * can be transformed by button presses and axes values, based on this._mapping.
  72543. *
  72544. * @param scene scene in which the meshes exist
  72545. * @param meshes list of meshes that make up the controller model to process
  72546. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72547. */
  72548. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72549. var loadedMeshInfo = null;
  72550. // Create a new mesh to contain the glTF hierarchy
  72551. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72552. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72553. var childMesh = null;
  72554. for (var i = 0; i < meshes.length; i++) {
  72555. var mesh = meshes[i];
  72556. if (!mesh.parent) {
  72557. // Exclude controller meshes from picking results
  72558. mesh.isPickable = false;
  72559. // Handle root node, attach to the new parentMesh
  72560. childMesh = mesh;
  72561. break;
  72562. }
  72563. }
  72564. if (childMesh) {
  72565. childMesh.setParent(parentMesh);
  72566. // Create our mesh info. Note that this method will always return non-null.
  72567. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72568. }
  72569. else {
  72570. BABYLON.Tools.Warn('Could not find root node in model file.');
  72571. }
  72572. return loadedMeshInfo;
  72573. };
  72574. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72575. var loadedMeshInfo = new LoadedMeshInfo();
  72576. var i;
  72577. loadedMeshInfo.rootNode = rootNode;
  72578. // Reset the caches
  72579. loadedMeshInfo.buttonMeshes = {};
  72580. loadedMeshInfo.axisMeshes = {};
  72581. // Button Meshes
  72582. for (i = 0; i < this._mapping.buttons.length; i++) {
  72583. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72584. if (!buttonMeshName) {
  72585. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72586. continue;
  72587. }
  72588. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72589. if (!buttonMesh) {
  72590. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72591. continue;
  72592. }
  72593. var buttonMeshInfo = {
  72594. index: i,
  72595. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72596. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72597. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72598. };
  72599. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72600. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72601. }
  72602. else {
  72603. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72604. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72605. '(VALUE: ' + !!buttonMeshInfo.value +
  72606. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72607. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72608. ')');
  72609. }
  72610. }
  72611. // Axis Meshes
  72612. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72613. var axisMeshName = this._mapping.axisMeshNames[i];
  72614. if (!axisMeshName) {
  72615. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72616. continue;
  72617. }
  72618. var axisMesh = getChildByName(rootNode, axisMeshName);
  72619. if (!axisMesh) {
  72620. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72621. continue;
  72622. }
  72623. var axisMeshInfo = {
  72624. index: i,
  72625. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72626. min: getImmediateChildByName(axisMesh, 'MIN'),
  72627. max: getImmediateChildByName(axisMesh, 'MAX')
  72628. };
  72629. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72630. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72631. }
  72632. else {
  72633. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72634. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72635. '(VALUE: ' + !!axisMeshInfo.value +
  72636. ', MIN: ' + !!axisMeshInfo.min +
  72637. ', MAX:' + !!axisMeshInfo.max +
  72638. ')');
  72639. }
  72640. }
  72641. // Pointing Ray
  72642. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72643. if (!loadedMeshInfo.pointingPoseNode) {
  72644. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72645. }
  72646. else {
  72647. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72648. }
  72649. return loadedMeshInfo;
  72650. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72651. function getChildByName(node, name) {
  72652. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72653. }
  72654. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72655. function getImmediateChildByName(node, name) {
  72656. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72657. }
  72658. };
  72659. /**
  72660. * Gets the ray of the controller in the direction the controller is pointing
  72661. * @param length the length the resulting ray should be
  72662. * @returns a ray in the direction the controller is pointing
  72663. */
  72664. WindowsMotionController.prototype.getForwardRay = function (length) {
  72665. if (length === void 0) { length = 100; }
  72666. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72667. return _super.prototype.getForwardRay.call(this, length);
  72668. }
  72669. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72670. var origin = m.getTranslation();
  72671. var forward = new BABYLON.Vector3(0, 0, -1);
  72672. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72673. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72674. return new BABYLON.Ray(origin, direction, length);
  72675. };
  72676. /**
  72677. * Disposes of the controller
  72678. */
  72679. WindowsMotionController.prototype.dispose = function () {
  72680. _super.prototype.dispose.call(this);
  72681. this.onTrackpadChangedObservable.clear();
  72682. };
  72683. /**
  72684. * The base url used to load the left and right controller models
  72685. */
  72686. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72687. /**
  72688. * The name of the left controller model file
  72689. */
  72690. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72691. /**
  72692. * The name of the right controller model file
  72693. */
  72694. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72695. /**
  72696. * The controller name prefix for this controller type
  72697. */
  72698. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72699. /**
  72700. * The controller id pattern for this controller type
  72701. */
  72702. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72703. return WindowsMotionController;
  72704. }(BABYLON.WebVRController));
  72705. BABYLON.WindowsMotionController = WindowsMotionController;
  72706. })(BABYLON || (BABYLON = {}));
  72707. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72708. var BABYLON;
  72709. (function (BABYLON) {
  72710. /**
  72711. * Gear VR Controller
  72712. */
  72713. var GearVRController = /** @class */ (function (_super) {
  72714. __extends(GearVRController, _super);
  72715. /**
  72716. * Creates a new GearVRController from a gamepad
  72717. * @param vrGamepad the gamepad that the controller should be created from
  72718. */
  72719. function GearVRController(vrGamepad) {
  72720. var _this = _super.call(this, vrGamepad) || this;
  72721. _this._maxRotationDistFromHeadset = Math.PI / 5;
  72722. _this._draggedRoomRotation = 0;
  72723. _this._tmpVector = new BABYLON.Vector3();
  72724. _this._buttonIndexToObservableNameMap = [
  72725. 'onTrackpadChangedObservable',
  72726. 'onTriggerStateChangedObservable' // Trigger
  72727. ];
  72728. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72729. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72730. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  72731. return _this;
  72732. }
  72733. /**
  72734. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72735. * @param poseData raw pose fromthe device
  72736. */
  72737. GearVRController.prototype.updateFromDevice = function (poseData) {
  72738. _super.prototype.updateFromDevice.call(this, poseData);
  72739. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  72740. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  72741. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  72742. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  72743. // Find the radian distance away that the headset is from the controllers rotation
  72744. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  72745. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  72746. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  72747. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  72748. this._draggedRoomRotation += rotationAmount;
  72749. // Rotate controller around headset
  72750. var sin = Math.sin(-rotationAmount);
  72751. var cos = Math.cos(-rotationAmount);
  72752. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  72753. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  72754. }
  72755. }
  72756. }
  72757. };
  72758. /**
  72759. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72760. * @param scene scene in which to add meshes
  72761. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72762. */
  72763. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72764. var _this = this;
  72765. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72766. // Offset the controller so it will rotate around the users wrist
  72767. var mesh = new BABYLON.Mesh("", scene);
  72768. newMeshes[1].parent = mesh;
  72769. newMeshes[1].position.z = -0.15;
  72770. _this._defaultModel = mesh;
  72771. _this.attachToMesh(_this._defaultModel);
  72772. if (meshLoaded) {
  72773. meshLoaded(_this._defaultModel);
  72774. }
  72775. });
  72776. };
  72777. /**
  72778. * Called once for each button that changed state since the last frame
  72779. * @param buttonIdx Which button index changed
  72780. * @param state New state of the button
  72781. * @param changes Which properties on the state changed since last frame
  72782. */
  72783. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72784. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72785. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72786. // Only emit events for buttons that we know how to map from index to observable
  72787. var observable = this[observableName];
  72788. if (observable) {
  72789. observable.notifyObservers(state);
  72790. }
  72791. }
  72792. };
  72793. /**
  72794. * Base Url for the controller model.
  72795. */
  72796. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72797. /**
  72798. * File name for the controller model.
  72799. */
  72800. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72801. /**
  72802. * Gamepad Id prefix used to identify this controller.
  72803. */
  72804. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72805. return GearVRController;
  72806. }(BABYLON.WebVRController));
  72807. BABYLON.GearVRController = GearVRController;
  72808. })(BABYLON || (BABYLON = {}));
  72809. //# sourceMappingURL=babylon.gearVRController.js.map
  72810. var BABYLON;
  72811. (function (BABYLON) {
  72812. /**
  72813. * Google Daydream controller
  72814. */
  72815. var DaydreamController = /** @class */ (function (_super) {
  72816. __extends(DaydreamController, _super);
  72817. /**
  72818. * Creates a new DaydreamController from a gamepad
  72819. * @param vrGamepad the gamepad that the controller should be created from
  72820. */
  72821. function DaydreamController(vrGamepad) {
  72822. var _this = _super.call(this, vrGamepad) || this;
  72823. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72824. return _this;
  72825. }
  72826. /**
  72827. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72828. * @param scene scene in which to add meshes
  72829. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72830. */
  72831. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72832. var _this = this;
  72833. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72834. _this._defaultModel = newMeshes[1];
  72835. _this.attachToMesh(_this._defaultModel);
  72836. if (meshLoaded) {
  72837. meshLoaded(_this._defaultModel);
  72838. }
  72839. });
  72840. };
  72841. /**
  72842. * Called once for each button that changed state since the last frame
  72843. * @param buttonIdx Which button index changed
  72844. * @param state New state of the button
  72845. * @param changes Which properties on the state changed since last frame
  72846. */
  72847. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72848. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72849. if (buttonIdx === 0) {
  72850. var observable = this.onTriggerStateChangedObservable;
  72851. if (observable) {
  72852. observable.notifyObservers(state);
  72853. }
  72854. }
  72855. else {
  72856. // If the app or home buttons are ever made available
  72857. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72858. }
  72859. };
  72860. /**
  72861. * Base Url for the controller model.
  72862. */
  72863. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72864. /**
  72865. * File name for the controller model.
  72866. */
  72867. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72868. /**
  72869. * Gamepad Id prefix used to identify Daydream Controller.
  72870. */
  72871. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72872. return DaydreamController;
  72873. }(BABYLON.WebVRController));
  72874. BABYLON.DaydreamController = DaydreamController;
  72875. })(BABYLON || (BABYLON = {}));
  72876. //# sourceMappingURL=babylon.daydreamController.js.map
  72877. var BABYLON;
  72878. (function (BABYLON) {
  72879. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  72880. get: function () {
  72881. if (!this._gamepadManager) {
  72882. this._gamepadManager = new BABYLON.GamepadManager(this);
  72883. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  72884. if (!component) {
  72885. component = new GamepadSystemSceneComponent(this);
  72886. this._addComponent(component);
  72887. }
  72888. }
  72889. return this._gamepadManager;
  72890. },
  72891. enumerable: true,
  72892. configurable: true
  72893. });
  72894. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  72895. this.add(new BABYLON.FreeCameraGamepadInput());
  72896. return this;
  72897. };
  72898. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  72899. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  72900. return this;
  72901. };
  72902. /**
  72903. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  72904. */
  72905. var GamepadSystemSceneComponent = /** @class */ (function () {
  72906. /**
  72907. * Creates a new instance of the component for the given scene
  72908. * @param scene Defines the scene to register the component in
  72909. */
  72910. function GamepadSystemSceneComponent(scene) {
  72911. /**
  72912. * The component name helpfull to identify the component in the list of scene components.
  72913. */
  72914. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  72915. this.scene = scene;
  72916. }
  72917. /**
  72918. * Registers the component in a given scene
  72919. */
  72920. GamepadSystemSceneComponent.prototype.register = function () {
  72921. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  72922. };
  72923. /**
  72924. * Rebuilds the elements related to this component in case of
  72925. * context lost for instance.
  72926. */
  72927. GamepadSystemSceneComponent.prototype.rebuild = function () {
  72928. // Nothing to do for gamepads
  72929. };
  72930. /**
  72931. * Disposes the component and the associated ressources
  72932. */
  72933. GamepadSystemSceneComponent.prototype.dispose = function () {
  72934. var gamepadManager = this.scene._gamepadManager;
  72935. if (gamepadManager) {
  72936. gamepadManager.dispose();
  72937. this.scene._gamepadManager = null;
  72938. }
  72939. };
  72940. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  72941. var gamepadManager = this.scene._gamepadManager;
  72942. if (gamepadManager && gamepadManager._isMonitoring) {
  72943. gamepadManager._checkGamepadsStatus();
  72944. }
  72945. };
  72946. return GamepadSystemSceneComponent;
  72947. }());
  72948. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  72949. })(BABYLON || (BABYLON = {}));
  72950. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  72951. var BABYLON;
  72952. (function (BABYLON) {
  72953. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  72954. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  72955. });
  72956. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  72957. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  72958. });
  72959. var FollowCamera = /** @class */ (function (_super) {
  72960. __extends(FollowCamera, _super);
  72961. function FollowCamera(name, position, scene, lockedTarget) {
  72962. if (lockedTarget === void 0) { lockedTarget = null; }
  72963. var _this = _super.call(this, name, position, scene) || this;
  72964. _this.radius = 12;
  72965. _this.rotationOffset = 0;
  72966. _this.heightOffset = 4;
  72967. _this.cameraAcceleration = 0.05;
  72968. _this.maxCameraSpeed = 20;
  72969. _this.lockedTarget = lockedTarget;
  72970. return _this;
  72971. }
  72972. FollowCamera.prototype.getRadians = function (degrees) {
  72973. return degrees * Math.PI / 180;
  72974. };
  72975. FollowCamera.prototype.follow = function (cameraTarget) {
  72976. if (!cameraTarget)
  72977. return;
  72978. var yRotation;
  72979. if (cameraTarget.rotationQuaternion) {
  72980. var rotMatrix = new BABYLON.Matrix();
  72981. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72982. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72983. }
  72984. else {
  72985. yRotation = cameraTarget.rotation.y;
  72986. }
  72987. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72988. var targetPosition = cameraTarget.getAbsolutePosition();
  72989. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72990. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72991. var dx = targetX - this.position.x;
  72992. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72993. var dz = (targetZ) - this.position.z;
  72994. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72995. var vy = dy * this.cameraAcceleration;
  72996. var vz = dz * this.cameraAcceleration * 2;
  72997. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72998. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72999. }
  73000. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73001. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73002. }
  73003. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73004. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73005. }
  73006. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73007. this.setTarget(targetPosition);
  73008. };
  73009. FollowCamera.prototype._checkInputs = function () {
  73010. _super.prototype._checkInputs.call(this);
  73011. if (this.lockedTarget) {
  73012. this.follow(this.lockedTarget);
  73013. }
  73014. };
  73015. FollowCamera.prototype.getClassName = function () {
  73016. return "FollowCamera";
  73017. };
  73018. __decorate([
  73019. BABYLON.serialize()
  73020. ], FollowCamera.prototype, "radius", void 0);
  73021. __decorate([
  73022. BABYLON.serialize()
  73023. ], FollowCamera.prototype, "rotationOffset", void 0);
  73024. __decorate([
  73025. BABYLON.serialize()
  73026. ], FollowCamera.prototype, "heightOffset", void 0);
  73027. __decorate([
  73028. BABYLON.serialize()
  73029. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73030. __decorate([
  73031. BABYLON.serialize()
  73032. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73033. __decorate([
  73034. BABYLON.serializeAsMeshReference("lockedTargetId")
  73035. ], FollowCamera.prototype, "lockedTarget", void 0);
  73036. return FollowCamera;
  73037. }(BABYLON.TargetCamera));
  73038. BABYLON.FollowCamera = FollowCamera;
  73039. var ArcFollowCamera = /** @class */ (function (_super) {
  73040. __extends(ArcFollowCamera, _super);
  73041. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73042. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73043. _this.alpha = alpha;
  73044. _this.beta = beta;
  73045. _this.radius = radius;
  73046. _this.target = target;
  73047. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73048. _this.follow();
  73049. return _this;
  73050. }
  73051. ArcFollowCamera.prototype.follow = function () {
  73052. if (!this.target) {
  73053. return;
  73054. }
  73055. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73056. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73057. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73058. var targetPosition = this.target.getAbsolutePosition();
  73059. this.position = targetPosition.add(this._cartesianCoordinates);
  73060. this.setTarget(targetPosition);
  73061. };
  73062. ArcFollowCamera.prototype._checkInputs = function () {
  73063. _super.prototype._checkInputs.call(this);
  73064. this.follow();
  73065. };
  73066. ArcFollowCamera.prototype.getClassName = function () {
  73067. return "ArcFollowCamera";
  73068. };
  73069. return ArcFollowCamera;
  73070. }(BABYLON.TargetCamera));
  73071. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73072. })(BABYLON || (BABYLON = {}));
  73073. //# sourceMappingURL=babylon.followCamera.js.map
  73074. var BABYLON;
  73075. (function (BABYLON) {
  73076. // We're mainly based on the logic defined into the FreeCamera code
  73077. var UniversalCamera = /** @class */ (function (_super) {
  73078. __extends(UniversalCamera, _super);
  73079. //-- end properties for backward compatibility for inputs
  73080. function UniversalCamera(name, position, scene) {
  73081. var _this = _super.call(this, name, position, scene) || this;
  73082. _this.inputs.addGamepad();
  73083. return _this;
  73084. }
  73085. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73086. //-- Begin properties for backward compatibility for inputs
  73087. get: function () {
  73088. var gamepad = this.inputs.attached["gamepad"];
  73089. if (gamepad)
  73090. return gamepad.gamepadAngularSensibility;
  73091. return 0;
  73092. },
  73093. set: function (value) {
  73094. var gamepad = this.inputs.attached["gamepad"];
  73095. if (gamepad)
  73096. gamepad.gamepadAngularSensibility = value;
  73097. },
  73098. enumerable: true,
  73099. configurable: true
  73100. });
  73101. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73102. get: function () {
  73103. var gamepad = this.inputs.attached["gamepad"];
  73104. if (gamepad)
  73105. return gamepad.gamepadMoveSensibility;
  73106. return 0;
  73107. },
  73108. set: function (value) {
  73109. var gamepad = this.inputs.attached["gamepad"];
  73110. if (gamepad)
  73111. gamepad.gamepadMoveSensibility = value;
  73112. },
  73113. enumerable: true,
  73114. configurable: true
  73115. });
  73116. UniversalCamera.prototype.getClassName = function () {
  73117. return "UniversalCamera";
  73118. };
  73119. return UniversalCamera;
  73120. }(BABYLON.TouchCamera));
  73121. BABYLON.UniversalCamera = UniversalCamera;
  73122. })(BABYLON || (BABYLON = {}));
  73123. //# sourceMappingURL=babylon.universalCamera.js.map
  73124. var BABYLON;
  73125. (function (BABYLON) {
  73126. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  73127. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  73128. });
  73129. // We're mainly based on the logic defined into the FreeCamera code
  73130. var GamepadCamera = /** @class */ (function (_super) {
  73131. __extends(GamepadCamera, _super);
  73132. //-- end properties for backward compatibility for inputs
  73133. function GamepadCamera(name, position, scene) {
  73134. return _super.call(this, name, position, scene) || this;
  73135. }
  73136. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73137. //-- Begin properties for backward compatibility for inputs
  73138. get: function () {
  73139. var gamepad = this.inputs.attached["gamepad"];
  73140. if (gamepad)
  73141. return gamepad.gamepadAngularSensibility;
  73142. return 0;
  73143. },
  73144. set: function (value) {
  73145. var gamepad = this.inputs.attached["gamepad"];
  73146. if (gamepad)
  73147. gamepad.gamepadAngularSensibility = value;
  73148. },
  73149. enumerable: true,
  73150. configurable: true
  73151. });
  73152. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73153. get: function () {
  73154. var gamepad = this.inputs.attached["gamepad"];
  73155. if (gamepad)
  73156. return gamepad.gamepadMoveSensibility;
  73157. return 0;
  73158. },
  73159. set: function (value) {
  73160. var gamepad = this.inputs.attached["gamepad"];
  73161. if (gamepad)
  73162. gamepad.gamepadMoveSensibility = value;
  73163. },
  73164. enumerable: true,
  73165. configurable: true
  73166. });
  73167. GamepadCamera.prototype.getClassName = function () {
  73168. return "GamepadCamera";
  73169. };
  73170. return GamepadCamera;
  73171. }(BABYLON.UniversalCamera));
  73172. BABYLON.GamepadCamera = GamepadCamera;
  73173. })(BABYLON || (BABYLON = {}));
  73174. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73175. var BABYLON;
  73176. (function (BABYLON) {
  73177. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73178. function PostProcessRenderPipelineManager() {
  73179. this._renderPipelines = {};
  73180. }
  73181. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73182. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73183. };
  73184. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73185. if (unique === void 0) { unique = false; }
  73186. var renderPipeline = this._renderPipelines[renderPipelineName];
  73187. if (!renderPipeline) {
  73188. return;
  73189. }
  73190. renderPipeline._attachCameras(cameras, unique);
  73191. };
  73192. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73193. var renderPipeline = this._renderPipelines[renderPipelineName];
  73194. if (!renderPipeline) {
  73195. return;
  73196. }
  73197. renderPipeline._detachCameras(cameras);
  73198. };
  73199. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73200. var renderPipeline = this._renderPipelines[renderPipelineName];
  73201. if (!renderPipeline) {
  73202. return;
  73203. }
  73204. renderPipeline._enableEffect(renderEffectName, cameras);
  73205. };
  73206. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73207. var renderPipeline = this._renderPipelines[renderPipelineName];
  73208. if (!renderPipeline) {
  73209. return;
  73210. }
  73211. renderPipeline._disableEffect(renderEffectName, cameras);
  73212. };
  73213. PostProcessRenderPipelineManager.prototype.update = function () {
  73214. for (var renderPipelineName in this._renderPipelines) {
  73215. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73216. var pipeline = this._renderPipelines[renderPipelineName];
  73217. if (!pipeline.isSupported) {
  73218. pipeline.dispose();
  73219. delete this._renderPipelines[renderPipelineName];
  73220. }
  73221. else {
  73222. pipeline._update();
  73223. }
  73224. }
  73225. }
  73226. };
  73227. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73228. for (var renderPipelineName in this._renderPipelines) {
  73229. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73230. var pipeline = this._renderPipelines[renderPipelineName];
  73231. pipeline._rebuild();
  73232. }
  73233. }
  73234. };
  73235. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73236. for (var renderPipelineName in this._renderPipelines) {
  73237. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73238. var pipeline = this._renderPipelines[renderPipelineName];
  73239. pipeline.dispose();
  73240. }
  73241. }
  73242. };
  73243. return PostProcessRenderPipelineManager;
  73244. }());
  73245. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73246. })(BABYLON || (BABYLON = {}));
  73247. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73248. var BABYLON;
  73249. (function (BABYLON) {
  73250. /**
  73251. * This represents a set of one or more post processes in Babylon.
  73252. * A post process can be used to apply a shader to a texture after it is rendered.
  73253. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73254. */
  73255. var PostProcessRenderEffect = /** @class */ (function () {
  73256. /**
  73257. * Instantiates a post process render effect.
  73258. * A post process can be used to apply a shader to a texture after it is rendered.
  73259. * @param engine The engine the effect is tied to
  73260. * @param name The name of the effect
  73261. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73262. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73263. */
  73264. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73265. this._name = name;
  73266. this._singleInstance = singleInstance || true;
  73267. this._getPostProcesses = getPostProcesses;
  73268. this._cameras = {};
  73269. this._indicesForCamera = {};
  73270. this._postProcesses = {};
  73271. }
  73272. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73273. /**
  73274. * Checks if all the post processes in the effect are supported.
  73275. */
  73276. get: function () {
  73277. for (var index in this._postProcesses) {
  73278. if (this._postProcesses.hasOwnProperty(index)) {
  73279. var pps = this._postProcesses[index];
  73280. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73281. if (!pps[ppIndex].isSupported) {
  73282. return false;
  73283. }
  73284. }
  73285. }
  73286. }
  73287. return true;
  73288. },
  73289. enumerable: true,
  73290. configurable: true
  73291. });
  73292. /**
  73293. * Updates the current state of the effect
  73294. */
  73295. PostProcessRenderEffect.prototype._update = function () {
  73296. };
  73297. /**
  73298. * Attaches the effect on cameras
  73299. * @param cameras The camera to attach to.
  73300. */
  73301. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73302. var _this = this;
  73303. var cameraKey;
  73304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73305. if (!cams) {
  73306. return;
  73307. }
  73308. for (var i = 0; i < cams.length; i++) {
  73309. var camera = cams[i];
  73310. var cameraName = camera.name;
  73311. if (this._singleInstance) {
  73312. cameraKey = 0;
  73313. }
  73314. else {
  73315. cameraKey = cameraName;
  73316. }
  73317. if (!this._postProcesses[cameraKey]) {
  73318. var postProcess = this._getPostProcesses();
  73319. if (postProcess) {
  73320. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73321. }
  73322. }
  73323. if (!this._indicesForCamera[cameraName]) {
  73324. this._indicesForCamera[cameraName] = [];
  73325. }
  73326. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73327. var index = camera.attachPostProcess(postProcess);
  73328. _this._indicesForCamera[cameraName].push(index);
  73329. });
  73330. if (!this._cameras[cameraName]) {
  73331. this._cameras[cameraName] = camera;
  73332. }
  73333. }
  73334. };
  73335. /**
  73336. * Detatches the effect on cameras
  73337. * @param cameras The camera to detatch from.
  73338. */
  73339. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73340. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73341. if (!cams) {
  73342. return;
  73343. }
  73344. for (var i = 0; i < cams.length; i++) {
  73345. var camera = cams[i];
  73346. var cameraName = camera.name;
  73347. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73348. camera.detachPostProcess(postProcess);
  73349. });
  73350. if (this._cameras[cameraName]) {
  73351. //this._indicesForCamera.splice(index, 1);
  73352. this._cameras[cameraName] = null;
  73353. }
  73354. }
  73355. };
  73356. /**
  73357. * Enables the effect on given cameras
  73358. * @param cameras The camera to enable.
  73359. */
  73360. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73361. var _this = this;
  73362. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73363. if (!cams) {
  73364. return;
  73365. }
  73366. for (var i = 0; i < cams.length; i++) {
  73367. var camera = cams[i];
  73368. var cameraName = camera.name;
  73369. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73370. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73371. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73372. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73373. });
  73374. }
  73375. }
  73376. }
  73377. };
  73378. /**
  73379. * Disables the effect on the given cameras
  73380. * @param cameras The camera to disable.
  73381. */
  73382. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73383. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73384. if (!cams) {
  73385. return;
  73386. }
  73387. for (var i = 0; i < cams.length; i++) {
  73388. var camera = cams[i];
  73389. var cameraName = camera.name;
  73390. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73391. camera.detachPostProcess(postProcess);
  73392. });
  73393. }
  73394. };
  73395. /**
  73396. * Gets a list of the post processes contained in the effect.
  73397. * @param camera The camera to get the post processes on.
  73398. * @returns The list of the post processes in the effect.
  73399. */
  73400. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73401. if (this._singleInstance) {
  73402. return this._postProcesses[0];
  73403. }
  73404. else {
  73405. if (!camera) {
  73406. return null;
  73407. }
  73408. return this._postProcesses[camera.name];
  73409. }
  73410. };
  73411. return PostProcessRenderEffect;
  73412. }());
  73413. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73414. })(BABYLON || (BABYLON = {}));
  73415. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73416. var BABYLON;
  73417. (function (BABYLON) {
  73418. var PostProcessRenderPipeline = /** @class */ (function () {
  73419. function PostProcessRenderPipeline(engine, name) {
  73420. this.engine = engine;
  73421. this._name = name;
  73422. this._renderEffects = {};
  73423. this._renderEffectsForIsolatedPass = new Array();
  73424. this._cameras = [];
  73425. }
  73426. PostProcessRenderPipeline.prototype.getClassName = function () {
  73427. return "PostProcessRenderPipeline";
  73428. };
  73429. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73430. get: function () {
  73431. for (var renderEffectName in this._renderEffects) {
  73432. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73433. if (!this._renderEffects[renderEffectName].isSupported) {
  73434. return false;
  73435. }
  73436. }
  73437. }
  73438. return true;
  73439. },
  73440. enumerable: true,
  73441. configurable: true
  73442. });
  73443. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73444. this._renderEffects[renderEffect._name] = renderEffect;
  73445. };
  73446. // private
  73447. PostProcessRenderPipeline.prototype._rebuild = function () {
  73448. };
  73449. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73450. var renderEffects = this._renderEffects[renderEffectName];
  73451. if (!renderEffects) {
  73452. return;
  73453. }
  73454. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73455. };
  73456. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73457. var renderEffects = this._renderEffects[renderEffectName];
  73458. if (!renderEffects) {
  73459. return;
  73460. }
  73461. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73462. };
  73463. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73464. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73465. if (!cams) {
  73466. return;
  73467. }
  73468. var indicesToDelete = [];
  73469. var i;
  73470. for (i = 0; i < cams.length; i++) {
  73471. var camera = cams[i];
  73472. var cameraName = camera.name;
  73473. if (this._cameras.indexOf(camera) === -1) {
  73474. this._cameras[cameraName] = camera;
  73475. }
  73476. else if (unique) {
  73477. indicesToDelete.push(i);
  73478. }
  73479. }
  73480. for (i = 0; i < indicesToDelete.length; i++) {
  73481. cameras.splice(indicesToDelete[i], 1);
  73482. }
  73483. for (var renderEffectName in this._renderEffects) {
  73484. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73485. this._renderEffects[renderEffectName]._attachCameras(cams);
  73486. }
  73487. }
  73488. };
  73489. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73490. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73491. if (!cams) {
  73492. return;
  73493. }
  73494. for (var renderEffectName in this._renderEffects) {
  73495. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73496. this._renderEffects[renderEffectName]._detachCameras(cams);
  73497. }
  73498. }
  73499. for (var i = 0; i < cams.length; i++) {
  73500. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73501. }
  73502. };
  73503. PostProcessRenderPipeline.prototype._update = function () {
  73504. for (var renderEffectName in this._renderEffects) {
  73505. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73506. this._renderEffects[renderEffectName]._update();
  73507. }
  73508. }
  73509. for (var i = 0; i < this._cameras.length; i++) {
  73510. var cameraName = this._cameras[i].name;
  73511. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73512. this._renderEffectsForIsolatedPass[cameraName]._update();
  73513. }
  73514. }
  73515. };
  73516. PostProcessRenderPipeline.prototype._reset = function () {
  73517. this._renderEffects = {};
  73518. this._renderEffectsForIsolatedPass = new Array();
  73519. };
  73520. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73521. // 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)
  73522. var effectKeys = Object.keys(this._renderEffects);
  73523. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73524. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73525. if (postProcesses) {
  73526. postProcesses[0].samples = sampleCount;
  73527. return true;
  73528. }
  73529. }
  73530. return false;
  73531. };
  73532. PostProcessRenderPipeline.prototype.dispose = function () {
  73533. // Must be implemented by children
  73534. };
  73535. __decorate([
  73536. BABYLON.serialize()
  73537. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73538. return PostProcessRenderPipeline;
  73539. }());
  73540. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73541. })(BABYLON || (BABYLON = {}));
  73542. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73543. var BABYLON;
  73544. (function (BABYLON) {
  73545. /**
  73546. * This represents a depth renderer in Babylon.
  73547. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73548. */
  73549. var DepthRenderer = /** @class */ (function () {
  73550. /**
  73551. * Instantiates a depth renderer
  73552. * @param scene The scene the renderer belongs to
  73553. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73554. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73555. */
  73556. function DepthRenderer(scene, type, camera) {
  73557. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73558. if (camera === void 0) { camera = null; }
  73559. var _this = this;
  73560. this._scene = scene;
  73561. this._camera = camera;
  73562. var engine = scene.getEngine();
  73563. // Render target
  73564. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73565. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73566. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73567. this._depthMap.refreshRate = 1;
  73568. this._depthMap.renderParticles = false;
  73569. this._depthMap.renderList = null;
  73570. // Camera to get depth map from to support multiple concurrent cameras
  73571. this._depthMap.activeCamera = this._camera;
  73572. this._depthMap.ignoreCameraViewport = true;
  73573. this._depthMap.useCameraPostProcesses = false;
  73574. // set default depth value to 1.0 (far away)
  73575. this._depthMap.onClearObservable.add(function (engine) {
  73576. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73577. });
  73578. // Custom render function
  73579. var renderSubMesh = function (subMesh) {
  73580. var mesh = subMesh.getRenderingMesh();
  73581. var scene = _this._scene;
  73582. var engine = scene.getEngine();
  73583. var material = subMesh.getMaterial();
  73584. if (!material) {
  73585. return;
  73586. }
  73587. // Culling and reverse (right handed system)
  73588. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73589. // Managing instances
  73590. var batch = mesh._getInstancesRenderList(subMesh._id);
  73591. if (batch.mustReturn) {
  73592. return;
  73593. }
  73594. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73595. var camera = _this._camera || scene.activeCamera;
  73596. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73597. engine.enableEffect(_this._effect);
  73598. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73599. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73600. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73601. // Alpha test
  73602. if (material && material.needAlphaTesting()) {
  73603. var alphaTexture = material.getAlphaTestTexture();
  73604. if (alphaTexture) {
  73605. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73606. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73607. }
  73608. }
  73609. // Bones
  73610. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73611. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73612. }
  73613. // Draw
  73614. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73615. }
  73616. };
  73617. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73618. var index;
  73619. if (depthOnlySubMeshes.length) {
  73620. engine.setColorWrite(false);
  73621. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73622. renderSubMesh(depthOnlySubMeshes.data[index]);
  73623. }
  73624. engine.setColorWrite(true);
  73625. }
  73626. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73627. renderSubMesh(opaqueSubMeshes.data[index]);
  73628. }
  73629. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73630. renderSubMesh(alphaTestSubMeshes.data[index]);
  73631. }
  73632. };
  73633. }
  73634. /**
  73635. * Creates the depth rendering effect and checks if the effect is ready.
  73636. * @param subMesh The submesh to be used to render the depth map of
  73637. * @param useInstances If multiple world instances should be used
  73638. * @returns if the depth renderer is ready to render the depth map
  73639. */
  73640. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73641. var material = subMesh.getMaterial();
  73642. if (material.disableDepthWrite) {
  73643. return false;
  73644. }
  73645. var defines = [];
  73646. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73647. var mesh = subMesh.getMesh();
  73648. // Alpha test
  73649. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73650. defines.push("#define ALPHATEST");
  73651. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73652. attribs.push(BABYLON.VertexBuffer.UVKind);
  73653. defines.push("#define UV1");
  73654. }
  73655. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73656. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73657. defines.push("#define UV2");
  73658. }
  73659. }
  73660. // Bones
  73661. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73664. if (mesh.numBoneInfluencers > 4) {
  73665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73667. }
  73668. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73669. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73670. }
  73671. else {
  73672. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73673. }
  73674. // Instances
  73675. if (useInstances) {
  73676. defines.push("#define INSTANCES");
  73677. attribs.push("world0");
  73678. attribs.push("world1");
  73679. attribs.push("world2");
  73680. attribs.push("world3");
  73681. }
  73682. // Get correct effect
  73683. var join = defines.join("\n");
  73684. if (this._cachedDefines !== join) {
  73685. this._cachedDefines = join;
  73686. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73687. }
  73688. return this._effect.isReady();
  73689. };
  73690. /**
  73691. * Gets the texture which the depth map will be written to.
  73692. * @returns The depth map texture
  73693. */
  73694. DepthRenderer.prototype.getDepthMap = function () {
  73695. return this._depthMap;
  73696. };
  73697. /**
  73698. * Disposes of the depth renderer.
  73699. */
  73700. DepthRenderer.prototype.dispose = function () {
  73701. this._depthMap.dispose();
  73702. };
  73703. return DepthRenderer;
  73704. }());
  73705. BABYLON.DepthRenderer = DepthRenderer;
  73706. })(BABYLON || (BABYLON = {}));
  73707. //# sourceMappingURL=babylon.depthRenderer.js.map
  73708. var BABYLON;
  73709. (function (BABYLON) {
  73710. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73711. __extends(SSAORenderingPipeline, _super);
  73712. /**
  73713. * @constructor
  73714. * @param {string} name - The rendering pipeline name
  73715. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73716. * @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 }
  73717. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73718. */
  73719. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73720. var _this = _super.call(this, scene.getEngine(), name) || this;
  73721. // Members
  73722. /**
  73723. * The PassPostProcess id in the pipeline that contains the original scene color
  73724. */
  73725. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73726. /**
  73727. * The SSAO PostProcess id in the pipeline
  73728. */
  73729. _this.SSAORenderEffect = "SSAORenderEffect";
  73730. /**
  73731. * The horizontal blur PostProcess id in the pipeline
  73732. */
  73733. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73734. /**
  73735. * The vertical blur PostProcess id in the pipeline
  73736. */
  73737. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73738. /**
  73739. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73740. */
  73741. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73742. /**
  73743. * The output strength of the SSAO post-process. Default value is 1.0.
  73744. */
  73745. _this.totalStrength = 1.0;
  73746. /**
  73747. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73748. */
  73749. _this.radius = 0.0001;
  73750. /**
  73751. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73752. * Must not be equal to fallOff and superior to fallOff.
  73753. * Default value is 0.975
  73754. */
  73755. _this.area = 0.0075;
  73756. /**
  73757. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73758. * Must not be equal to area and inferior to area.
  73759. * Default value is 0.0
  73760. */
  73761. _this.fallOff = 0.000001;
  73762. /**
  73763. * The base color of the SSAO post-process
  73764. * The final result is "base + ssao" between [0, 1]
  73765. */
  73766. _this.base = 0.5;
  73767. _this._firstUpdate = true;
  73768. _this._scene = scene;
  73769. // Set up assets
  73770. _this._createRandomTexture();
  73771. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73772. var ssaoRatio = ratio.ssaoRatio || ratio;
  73773. var combineRatio = ratio.combineRatio || ratio;
  73774. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73775. _this._createSSAOPostProcess(ssaoRatio);
  73776. _this._createBlurPostProcess(ssaoRatio);
  73777. _this._createSSAOCombinePostProcess(combineRatio);
  73778. // Set up pipeline
  73779. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73780. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73781. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73782. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73783. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73784. // Finish
  73785. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73786. if (cameras)
  73787. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73788. return _this;
  73789. }
  73790. // Public Methods
  73791. /**
  73792. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73793. */
  73794. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73795. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73796. for (var i = 0; i < this._scene.cameras.length; i++) {
  73797. var camera = this._scene.cameras[i];
  73798. this._originalColorPostProcess.dispose(camera);
  73799. this._ssaoPostProcess.dispose(camera);
  73800. this._blurHPostProcess.dispose(camera);
  73801. this._blurVPostProcess.dispose(camera);
  73802. this._ssaoCombinePostProcess.dispose(camera);
  73803. }
  73804. this._randomTexture.dispose();
  73805. if (disableDepthRender)
  73806. this._scene.disableDepthRenderer();
  73807. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73808. _super.prototype.dispose.call(this);
  73809. };
  73810. // Private Methods
  73811. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73812. var _this = this;
  73813. var size = 16;
  73814. 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);
  73815. 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);
  73816. this._blurHPostProcess.onActivateObservable.add(function () {
  73817. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73818. _this._blurHPostProcess.kernel = size * dw;
  73819. });
  73820. this._blurVPostProcess.onActivateObservable.add(function () {
  73821. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73822. _this._blurVPostProcess.kernel = size * dw;
  73823. });
  73824. };
  73825. SSAORenderingPipeline.prototype._rebuild = function () {
  73826. this._firstUpdate = true;
  73827. _super.prototype._rebuild.call(this);
  73828. };
  73829. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73830. var _this = this;
  73831. var numSamples = 16;
  73832. var sampleSphere = [
  73833. 0.5381, 0.1856, -0.4319,
  73834. 0.1379, 0.2486, 0.4430,
  73835. 0.3371, 0.5679, -0.0057,
  73836. -0.6999, -0.0451, -0.0019,
  73837. 0.0689, -0.1598, -0.8547,
  73838. 0.0560, 0.0069, -0.1843,
  73839. -0.0146, 0.1402, 0.0762,
  73840. 0.0100, -0.1924, -0.0344,
  73841. -0.3577, -0.5301, -0.4358,
  73842. -0.3169, 0.1063, 0.0158,
  73843. 0.0103, -0.5869, 0.0046,
  73844. -0.0897, -0.4940, 0.3287,
  73845. 0.7119, -0.0154, -0.0918,
  73846. -0.0533, 0.0596, -0.5411,
  73847. 0.0352, -0.0631, 0.5460,
  73848. -0.4776, 0.2847, -0.0271
  73849. ];
  73850. var samplesFactor = 1.0 / numSamples;
  73851. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73852. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73853. "area", "fallOff", "base", "range", "viewport"
  73854. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73855. this._ssaoPostProcess.onApply = function (effect) {
  73856. if (_this._firstUpdate) {
  73857. effect.setArray3("sampleSphere", sampleSphere);
  73858. effect.setFloat("samplesFactor", samplesFactor);
  73859. effect.setFloat("randTextureTiles", 4.0);
  73860. }
  73861. effect.setFloat("totalStrength", _this.totalStrength);
  73862. effect.setFloat("radius", _this.radius);
  73863. effect.setFloat("area", _this.area);
  73864. effect.setFloat("fallOff", _this.fallOff);
  73865. effect.setFloat("base", _this.base);
  73866. effect.setTexture("textureSampler", _this._depthTexture);
  73867. effect.setTexture("randomSampler", _this._randomTexture);
  73868. };
  73869. };
  73870. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73871. var _this = this;
  73872. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73873. this._ssaoCombinePostProcess.onApply = function (effect) {
  73874. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73875. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73876. };
  73877. };
  73878. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73879. var size = 512;
  73880. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73881. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73882. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73883. var context = this._randomTexture.getContext();
  73884. var rand = function (min, max) {
  73885. return Math.random() * (max - min) + min;
  73886. };
  73887. var randVector = BABYLON.Vector3.Zero();
  73888. for (var x = 0; x < size; x++) {
  73889. for (var y = 0; y < size; y++) {
  73890. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73891. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73892. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73893. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73894. context.fillRect(x, y, 1, 1);
  73895. }
  73896. }
  73897. this._randomTexture.update(false);
  73898. };
  73899. __decorate([
  73900. BABYLON.serialize()
  73901. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73902. __decorate([
  73903. BABYLON.serialize()
  73904. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73905. __decorate([
  73906. BABYLON.serialize()
  73907. ], SSAORenderingPipeline.prototype, "area", void 0);
  73908. __decorate([
  73909. BABYLON.serialize()
  73910. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73911. __decorate([
  73912. BABYLON.serialize()
  73913. ], SSAORenderingPipeline.prototype, "base", void 0);
  73914. return SSAORenderingPipeline;
  73915. }(BABYLON.PostProcessRenderPipeline));
  73916. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73917. })(BABYLON || (BABYLON = {}));
  73918. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73919. var BABYLON;
  73920. (function (BABYLON) {
  73921. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73922. __extends(SSAO2RenderingPipeline, _super);
  73923. /**
  73924. * @constructor
  73925. * @param {string} name - The rendering pipeline name
  73926. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73927. * @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 }
  73928. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73929. */
  73930. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73931. var _this = _super.call(this, scene.getEngine(), name) || this;
  73932. // Members
  73933. /**
  73934. * The PassPostProcess id in the pipeline that contains the original scene color
  73935. */
  73936. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73937. /**
  73938. * The SSAO PostProcess id in the pipeline
  73939. */
  73940. _this.SSAORenderEffect = "SSAORenderEffect";
  73941. /**
  73942. * The horizontal blur PostProcess id in the pipeline
  73943. */
  73944. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73945. /**
  73946. * The vertical blur PostProcess id in the pipeline
  73947. */
  73948. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73949. /**
  73950. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73951. */
  73952. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73953. /**
  73954. * The output strength of the SSAO post-process. Default value is 1.0.
  73955. */
  73956. _this.totalStrength = 1.0;
  73957. /**
  73958. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73959. */
  73960. _this.maxZ = 100.0;
  73961. /**
  73962. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73963. */
  73964. _this.minZAspect = 0.2;
  73965. /**
  73966. * Number of samples used for the SSAO calculations. Default value is 8
  73967. */
  73968. _this._samples = 8;
  73969. /**
  73970. * Are we using bilateral blur ?
  73971. */
  73972. _this._expensiveBlur = true;
  73973. /**
  73974. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73975. */
  73976. _this.radius = 2.0;
  73977. /**
  73978. * The base color of the SSAO post-process
  73979. * The final result is "base + ssao" between [0, 1]
  73980. */
  73981. _this.base = 0.1;
  73982. _this._firstUpdate = true;
  73983. _this._scene = scene;
  73984. _this._ratio = ratio;
  73985. if (!_this.isSupported) {
  73986. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73987. return _this;
  73988. }
  73989. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73990. var blurRatio = _this._ratio.blurRatio || ratio;
  73991. // Set up assets
  73992. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73993. _this._createRandomTexture();
  73994. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73995. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73996. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73997. _this._createSSAOPostProcess(1.0);
  73998. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73999. _this._createSSAOCombinePostProcess(blurRatio);
  74000. // Set up pipeline
  74001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74002. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74003. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74004. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74005. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74006. // Finish
  74007. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74008. if (cameras)
  74009. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74010. return _this;
  74011. }
  74012. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74013. get: function () {
  74014. return this._samples;
  74015. },
  74016. set: function (n) {
  74017. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74018. this._samples = n;
  74019. this._sampleSphere = this._generateHemisphere();
  74020. this._firstUpdate = true;
  74021. },
  74022. enumerable: true,
  74023. configurable: true
  74024. });
  74025. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74026. get: function () {
  74027. return this._expensiveBlur;
  74028. },
  74029. set: function (b) {
  74030. 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"]);
  74031. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74032. this._expensiveBlur = b;
  74033. this._firstUpdate = true;
  74034. },
  74035. enumerable: true,
  74036. configurable: true
  74037. });
  74038. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74039. /**
  74040. * Support test.
  74041. */
  74042. get: function () {
  74043. var engine = BABYLON.Engine.LastCreatedEngine;
  74044. if (!engine) {
  74045. return false;
  74046. }
  74047. return engine.getCaps().drawBuffersExtension;
  74048. },
  74049. enumerable: true,
  74050. configurable: true
  74051. });
  74052. // Public Methods
  74053. /**
  74054. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74055. */
  74056. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74057. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74058. for (var i = 0; i < this._scene.cameras.length; i++) {
  74059. var camera = this._scene.cameras[i];
  74060. this._originalColorPostProcess.dispose(camera);
  74061. this._ssaoPostProcess.dispose(camera);
  74062. this._blurHPostProcess.dispose(camera);
  74063. this._blurVPostProcess.dispose(camera);
  74064. this._ssaoCombinePostProcess.dispose(camera);
  74065. }
  74066. this._randomTexture.dispose();
  74067. if (disableGeometryBufferRenderer)
  74068. this._scene.disableGeometryBufferRenderer();
  74069. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74070. _super.prototype.dispose.call(this);
  74071. };
  74072. // Private Methods
  74073. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74074. var _this = this;
  74075. this._samplerOffsets = [];
  74076. var expensive = this.expensiveBlur;
  74077. for (var i = -8; i < 8; i++) {
  74078. this._samplerOffsets.push(i * 2 + 0.5);
  74079. }
  74080. 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");
  74081. this._blurHPostProcess.onApply = function (effect) {
  74082. if (!_this._scene.activeCamera) {
  74083. return;
  74084. }
  74085. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74086. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74087. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74088. effect.setFloat("radius", _this.radius);
  74089. effect.setTexture("depthSampler", _this._depthTexture);
  74090. if (_this._firstUpdate) {
  74091. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74092. }
  74093. };
  74094. 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");
  74095. this._blurVPostProcess.onApply = function (effect) {
  74096. if (!_this._scene.activeCamera) {
  74097. return;
  74098. }
  74099. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74100. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74101. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74102. effect.setFloat("radius", _this.radius);
  74103. effect.setTexture("depthSampler", _this._depthTexture);
  74104. if (_this._firstUpdate) {
  74105. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74106. _this._firstUpdate = false;
  74107. }
  74108. };
  74109. };
  74110. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74111. this._firstUpdate = true;
  74112. _super.prototype._rebuild.call(this);
  74113. };
  74114. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74115. var numSamples = this.samples;
  74116. var result = [];
  74117. var vector, scale;
  74118. var rand = function (min, max) {
  74119. return Math.random() * (max - min) + min;
  74120. };
  74121. var i = 0;
  74122. while (i < numSamples) {
  74123. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74124. vector.normalize();
  74125. scale = i / numSamples;
  74126. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74127. vector.scaleInPlace(scale);
  74128. result.push(vector.x, vector.y, vector.z);
  74129. i++;
  74130. }
  74131. return result;
  74132. };
  74133. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74134. var _this = this;
  74135. var numSamples = this.samples;
  74136. this._sampleSphere = this._generateHemisphere();
  74137. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74138. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74139. "base", "range", "projection", "near", "far", "texelSize",
  74140. "xViewport", "yViewport", "maxZ", "minZAspect"
  74141. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74142. this._ssaoPostProcess.onApply = function (effect) {
  74143. if (_this._firstUpdate) {
  74144. effect.setArray3("sampleSphere", _this._sampleSphere);
  74145. effect.setFloat("randTextureTiles", 4.0);
  74146. }
  74147. if (!_this._scene.activeCamera) {
  74148. return;
  74149. }
  74150. effect.setFloat("samplesFactor", 1 / _this.samples);
  74151. effect.setFloat("totalStrength", _this.totalStrength);
  74152. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74153. effect.setFloat("radius", _this.radius);
  74154. effect.setFloat("maxZ", _this.maxZ);
  74155. effect.setFloat("minZAspect", _this.minZAspect);
  74156. effect.setFloat("base", _this.base);
  74157. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74158. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74159. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74160. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74161. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74162. effect.setTexture("textureSampler", _this._depthTexture);
  74163. effect.setTexture("normalSampler", _this._normalTexture);
  74164. effect.setTexture("randomSampler", _this._randomTexture);
  74165. };
  74166. };
  74167. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74168. var _this = this;
  74169. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74170. this._ssaoCombinePostProcess.onApply = function (effect) {
  74171. var viewport = _this._scene.activeCamera.viewport;
  74172. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74173. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74174. };
  74175. };
  74176. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74177. var size = 512;
  74178. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74179. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74180. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74181. var context = this._randomTexture.getContext();
  74182. var rand = function (min, max) {
  74183. return Math.random() * (max - min) + min;
  74184. };
  74185. var randVector = BABYLON.Vector3.Zero();
  74186. for (var x = 0; x < size; x++) {
  74187. for (var y = 0; y < size; y++) {
  74188. randVector.x = rand(0.0, 1.0);
  74189. randVector.y = rand(0.0, 1.0);
  74190. randVector.z = 0.0;
  74191. randVector.normalize();
  74192. randVector.scaleInPlace(255);
  74193. randVector.x = Math.floor(randVector.x);
  74194. randVector.y = Math.floor(randVector.y);
  74195. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74196. context.fillRect(x, y, 1, 1);
  74197. }
  74198. }
  74199. this._randomTexture.update(false);
  74200. };
  74201. /**
  74202. * Serialize the rendering pipeline (Used when exporting)
  74203. * @returns the serialized object
  74204. */
  74205. SSAO2RenderingPipeline.prototype.serialize = function () {
  74206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74207. serializationObject.customType = "SSAO2RenderingPipeline";
  74208. return serializationObject;
  74209. };
  74210. /**
  74211. * Parse the serialized pipeline
  74212. * @param source Source pipeline.
  74213. * @param scene The scene to load the pipeline to.
  74214. * @param rootUrl The URL of the serialized pipeline.
  74215. * @returns An instantiated pipeline from the serialized object.
  74216. */
  74217. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74218. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74219. };
  74220. __decorate([
  74221. BABYLON.serialize()
  74222. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74223. __decorate([
  74224. BABYLON.serialize()
  74225. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74226. __decorate([
  74227. BABYLON.serialize()
  74228. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74229. __decorate([
  74230. BABYLON.serialize("samples")
  74231. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74232. __decorate([
  74233. BABYLON.serialize()
  74234. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74235. __decorate([
  74236. BABYLON.serialize("expensiveBlur")
  74237. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74238. __decorate([
  74239. BABYLON.serialize()
  74240. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74241. __decorate([
  74242. BABYLON.serialize()
  74243. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74244. return SSAO2RenderingPipeline;
  74245. }(BABYLON.PostProcessRenderPipeline));
  74246. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74247. })(BABYLON || (BABYLON = {}));
  74248. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74249. // BABYLON.JS Chromatic Aberration GLSL Shader
  74250. // Author: Olivier Guyot
  74251. // Separates very slightly R, G and B colors on the edges of the screen
  74252. // Inspired by Francois Tarlier & Martins Upitis
  74253. var BABYLON;
  74254. (function (BABYLON) {
  74255. var LensRenderingPipeline = /** @class */ (function (_super) {
  74256. __extends(LensRenderingPipeline, _super);
  74257. /**
  74258. * @constructor
  74259. *
  74260. * Effect parameters are as follow:
  74261. * {
  74262. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74263. * edge_blur: number; // from 0 to x (1 for realism)
  74264. * distortion: number; // from 0 to x (1 for realism)
  74265. * grain_amount: number; // from 0 to 1
  74266. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74267. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74268. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74269. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74270. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74271. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74272. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74273. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74274. * }
  74275. * Note: if an effect parameter is unset, effect is disabled
  74276. *
  74277. * @param {string} name - The rendering pipeline name
  74278. * @param {object} parameters - An object containing all parameters (see above)
  74279. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74280. * @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)
  74281. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74282. */
  74283. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74284. if (ratio === void 0) { ratio = 1.0; }
  74285. var _this = _super.call(this, scene.getEngine(), name) || this;
  74286. // Lens effects can be of the following:
  74287. // - chromatic aberration (slight shift of RGB colors)
  74288. // - blur on the edge of the lens
  74289. // - lens distortion
  74290. // - depth-of-field blur & highlights enhancing
  74291. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74292. // - grain effect (noise or custom texture)
  74293. // Two additional texture samplers are needed:
  74294. // - depth map (for depth-of-field)
  74295. // - grain texture
  74296. /**
  74297. * The chromatic aberration PostProcess id in the pipeline
  74298. */
  74299. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74300. /**
  74301. * The highlights enhancing PostProcess id in the pipeline
  74302. */
  74303. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74304. /**
  74305. * The depth-of-field PostProcess id in the pipeline
  74306. */
  74307. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74308. _this._scene = scene;
  74309. // Fetch texture samplers
  74310. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74311. if (parameters.grain_texture) {
  74312. _this._grainTexture = parameters.grain_texture;
  74313. }
  74314. else {
  74315. _this._createGrainTexture();
  74316. }
  74317. // save parameters
  74318. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74319. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74320. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74321. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74322. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74323. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74324. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74325. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74326. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74327. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74328. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74329. // Create effects
  74330. _this._createChromaticAberrationPostProcess(ratio);
  74331. _this._createHighlightsPostProcess(ratio);
  74332. _this._createDepthOfFieldPostProcess(ratio / 4);
  74333. // Set up pipeline
  74334. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74335. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74336. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74337. if (_this._highlightsGain === -1) {
  74338. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74339. }
  74340. // Finish
  74341. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74342. if (cameras) {
  74343. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74344. }
  74345. return _this;
  74346. }
  74347. // public methods (self explanatory)
  74348. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74349. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74350. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74351. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74352. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74353. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74354. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74355. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74356. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74357. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74358. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74359. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74360. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74361. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74362. };
  74363. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74364. this._highlightsPostProcess.updateEffect();
  74365. };
  74366. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74367. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74368. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74369. this._highlightsGain = amount;
  74370. };
  74371. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74372. if (this._highlightsGain === -1) {
  74373. this._highlightsGain = 1.0;
  74374. }
  74375. this._highlightsThreshold = amount;
  74376. };
  74377. LensRenderingPipeline.prototype.disableHighlights = function () {
  74378. this._highlightsGain = -1;
  74379. };
  74380. /**
  74381. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74382. */
  74383. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74384. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74385. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74386. this._chromaticAberrationPostProcess = null;
  74387. this._highlightsPostProcess = null;
  74388. this._depthOfFieldPostProcess = null;
  74389. this._grainTexture.dispose();
  74390. if (disableDepthRender)
  74391. this._scene.disableDepthRenderer();
  74392. };
  74393. // colors shifting and distortion
  74394. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74395. var _this = this;
  74396. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74397. [], // samplers
  74398. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74399. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74400. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74401. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74402. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74403. effect.setFloat('radialIntensity', 1);
  74404. effect.setFloat2('direction', 17, 17);
  74405. effect.setFloat2('centerPosition', 0.5, 0.5);
  74406. };
  74407. };
  74408. // highlights enhancing
  74409. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74410. var _this = this;
  74411. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74412. [], // samplers
  74413. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74414. this._highlightsPostProcess.onApply = function (effect) {
  74415. effect.setFloat('gain', _this._highlightsGain);
  74416. effect.setFloat('threshold', _this._highlightsThreshold);
  74417. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74418. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74419. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74420. };
  74421. };
  74422. // colors shifting and distortion
  74423. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74424. var _this = this;
  74425. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74426. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74427. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74428. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74429. this._depthOfFieldPostProcess.onApply = function (effect) {
  74430. effect.setTexture("depthSampler", _this._depthTexture);
  74431. effect.setTexture("grainSampler", _this._grainTexture);
  74432. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74433. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74434. effect.setFloat('grain_amount', _this._grainAmount);
  74435. effect.setBool('blur_noise', _this._blurNoise);
  74436. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74437. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74438. effect.setFloat('distortion', _this._distortion);
  74439. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74440. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74441. effect.setFloat('aperture', _this._dofAperture);
  74442. effect.setFloat('darken', _this._dofDarken);
  74443. effect.setFloat('edge_blur', _this._edgeBlur);
  74444. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74445. if (_this._scene.activeCamera) {
  74446. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74447. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74448. }
  74449. };
  74450. };
  74451. // creates a black and white random noise texture, 512x512
  74452. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74453. var size = 512;
  74454. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74455. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74456. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74457. var context = this._grainTexture.getContext();
  74458. var rand = function (min, max) {
  74459. return Math.random() * (max - min) + min;
  74460. };
  74461. var value;
  74462. for (var x = 0; x < size; x++) {
  74463. for (var y = 0; y < size; y++) {
  74464. value = Math.floor(rand(0.42, 0.58) * 255);
  74465. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74466. context.fillRect(x, y, 1, 1);
  74467. }
  74468. }
  74469. this._grainTexture.update(false);
  74470. };
  74471. return LensRenderingPipeline;
  74472. }(BABYLON.PostProcessRenderPipeline));
  74473. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74474. })(BABYLON || (BABYLON = {}));
  74475. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74476. var BABYLON;
  74477. (function (BABYLON) {
  74478. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74479. __extends(StandardRenderingPipeline, _super);
  74480. /**
  74481. * @constructor
  74482. * @param {string} name - The rendering pipeline name
  74483. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74484. * @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)
  74485. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74486. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74487. */
  74488. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74489. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74490. var _this = _super.call(this, scene.getEngine(), name) || this;
  74491. _this.downSampleX4PostProcess = null;
  74492. _this.brightPassPostProcess = null;
  74493. _this.blurHPostProcesses = [];
  74494. _this.blurVPostProcesses = [];
  74495. _this.textureAdderPostProcess = null;
  74496. _this.volumetricLightPostProcess = null;
  74497. _this.volumetricLightSmoothXPostProcess = null;
  74498. _this.volumetricLightSmoothYPostProcess = null;
  74499. _this.volumetricLightMergePostProces = null;
  74500. _this.volumetricLightFinalPostProcess = null;
  74501. _this.luminancePostProcess = null;
  74502. _this.luminanceDownSamplePostProcesses = [];
  74503. _this.hdrPostProcess = null;
  74504. _this.textureAdderFinalPostProcess = null;
  74505. _this.lensFlareFinalPostProcess = null;
  74506. _this.hdrFinalPostProcess = null;
  74507. _this.lensFlarePostProcess = null;
  74508. _this.lensFlareComposePostProcess = null;
  74509. _this.motionBlurPostProcess = null;
  74510. _this.depthOfFieldPostProcess = null;
  74511. // Values
  74512. _this.brightThreshold = 1.0;
  74513. _this.blurWidth = 512.0;
  74514. _this.horizontalBlur = false;
  74515. _this.exposure = 1.0;
  74516. _this.lensTexture = null;
  74517. _this.volumetricLightCoefficient = 0.2;
  74518. _this.volumetricLightPower = 4.0;
  74519. _this.volumetricLightBlurScale = 64.0;
  74520. _this.sourceLight = null;
  74521. _this.hdrMinimumLuminance = 1.0;
  74522. _this.hdrDecreaseRate = 0.5;
  74523. _this.hdrIncreaseRate = 0.5;
  74524. _this.lensColorTexture = null;
  74525. _this.lensFlareStrength = 20.0;
  74526. _this.lensFlareGhostDispersal = 1.4;
  74527. _this.lensFlareHaloWidth = 0.7;
  74528. _this.lensFlareDistortionStrength = 16.0;
  74529. _this.lensStarTexture = null;
  74530. _this.lensFlareDirtTexture = null;
  74531. _this.depthOfFieldDistance = 10.0;
  74532. _this.depthOfFieldBlurWidth = 64.0;
  74533. _this.motionStrength = 1.0;
  74534. // IAnimatable
  74535. _this.animations = [];
  74536. _this._currentDepthOfFieldSource = null;
  74537. _this._hdrCurrentLuminance = 1.0;
  74538. // Getters and setters
  74539. _this._bloomEnabled = true;
  74540. _this._depthOfFieldEnabled = false;
  74541. _this._vlsEnabled = false;
  74542. _this._lensFlareEnabled = false;
  74543. _this._hdrEnabled = false;
  74544. _this._motionBlurEnabled = false;
  74545. _this._motionBlurSamples = 64.0;
  74546. _this._volumetricLightStepsCount = 50.0;
  74547. _this._cameras = cameras || [];
  74548. // Initialize
  74549. _this._scene = scene;
  74550. _this._basePostProcess = originalPostProcess;
  74551. _this._ratio = ratio;
  74552. // Misc
  74553. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74554. // Finish
  74555. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74556. _this._buildPipeline();
  74557. return _this;
  74558. }
  74559. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74560. get: function () {
  74561. return this._bloomEnabled;
  74562. },
  74563. set: function (enabled) {
  74564. if (this._bloomEnabled === enabled) {
  74565. return;
  74566. }
  74567. this._bloomEnabled = enabled;
  74568. this._buildPipeline();
  74569. },
  74570. enumerable: true,
  74571. configurable: true
  74572. });
  74573. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74574. get: function () {
  74575. return this._depthOfFieldEnabled;
  74576. },
  74577. set: function (enabled) {
  74578. if (this._depthOfFieldEnabled === enabled) {
  74579. return;
  74580. }
  74581. this._depthOfFieldEnabled = enabled;
  74582. this._buildPipeline();
  74583. },
  74584. enumerable: true,
  74585. configurable: true
  74586. });
  74587. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74588. get: function () {
  74589. return this._lensFlareEnabled;
  74590. },
  74591. set: function (enabled) {
  74592. if (this._lensFlareEnabled === enabled) {
  74593. return;
  74594. }
  74595. this._lensFlareEnabled = enabled;
  74596. this._buildPipeline();
  74597. },
  74598. enumerable: true,
  74599. configurable: true
  74600. });
  74601. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74602. get: function () {
  74603. return this._hdrEnabled;
  74604. },
  74605. set: function (enabled) {
  74606. if (this._hdrEnabled === enabled) {
  74607. return;
  74608. }
  74609. this._hdrEnabled = enabled;
  74610. this._buildPipeline();
  74611. },
  74612. enumerable: true,
  74613. configurable: true
  74614. });
  74615. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74616. get: function () {
  74617. return this._vlsEnabled;
  74618. },
  74619. set: function (enabled) {
  74620. if (this._vlsEnabled === enabled) {
  74621. return;
  74622. }
  74623. if (enabled) {
  74624. var geometry = this._scene.enableGeometryBufferRenderer();
  74625. if (!geometry) {
  74626. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74627. return;
  74628. }
  74629. }
  74630. this._vlsEnabled = enabled;
  74631. this._buildPipeline();
  74632. },
  74633. enumerable: true,
  74634. configurable: true
  74635. });
  74636. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74637. get: function () {
  74638. return this._motionBlurEnabled;
  74639. },
  74640. set: function (enabled) {
  74641. if (this._motionBlurEnabled === enabled) {
  74642. return;
  74643. }
  74644. this._motionBlurEnabled = enabled;
  74645. this._buildPipeline();
  74646. },
  74647. enumerable: true,
  74648. configurable: true
  74649. });
  74650. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74651. get: function () {
  74652. return this._volumetricLightStepsCount;
  74653. },
  74654. set: function (count) {
  74655. if (this.volumetricLightPostProcess) {
  74656. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74657. }
  74658. this._volumetricLightStepsCount = count;
  74659. },
  74660. enumerable: true,
  74661. configurable: true
  74662. });
  74663. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74664. get: function () {
  74665. return this._motionBlurSamples;
  74666. },
  74667. set: function (samples) {
  74668. if (this.motionBlurPostProcess) {
  74669. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74670. }
  74671. this._motionBlurSamples = samples;
  74672. },
  74673. enumerable: true,
  74674. configurable: true
  74675. });
  74676. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74677. var _this = this;
  74678. var ratio = this._ratio;
  74679. var scene = this._scene;
  74680. this._disposePostProcesses();
  74681. this._reset();
  74682. // Create pass post-process
  74683. if (!this._basePostProcess) {
  74684. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74685. this.originalPostProcess.onApply = function (effect) {
  74686. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74687. };
  74688. }
  74689. else {
  74690. this.originalPostProcess = this._basePostProcess;
  74691. }
  74692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74693. this._currentDepthOfFieldSource = this.originalPostProcess;
  74694. if (this._bloomEnabled) {
  74695. // Create down sample X4 post-process
  74696. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74697. // Create bright pass post-process
  74698. this._createBrightPassPostProcess(scene, ratio / 2);
  74699. // Create gaussian blur post-processes (down sampling blurs)
  74700. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74701. // Create texture adder post-process
  74702. this._createTextureAdderPostProcess(scene, ratio);
  74703. // Create depth-of-field source post-process
  74704. 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);
  74705. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74706. }
  74707. if (this._vlsEnabled) {
  74708. // Create volumetric light
  74709. this._createVolumetricLightPostProcess(scene, ratio);
  74710. // Create volumetric light final post-process
  74711. 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);
  74712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74713. }
  74714. if (this._lensFlareEnabled) {
  74715. // Create lens flare post-process
  74716. this._createLensFlarePostProcess(scene, ratio);
  74717. // Create depth-of-field source post-process post lens-flare and disable it now
  74718. 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);
  74719. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74720. }
  74721. if (this._hdrEnabled) {
  74722. // Create luminance
  74723. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74724. // Create HDR
  74725. this._createHdrPostProcess(scene, ratio);
  74726. // Create depth-of-field source post-process post hdr and disable it now
  74727. 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);
  74728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74729. }
  74730. if (this._depthOfFieldEnabled) {
  74731. // Create gaussian blur used by depth-of-field
  74732. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74733. // Create depth-of-field post-process
  74734. this._createDepthOfFieldPostProcess(scene, ratio);
  74735. }
  74736. if (this._motionBlurEnabled) {
  74737. // Create motion blur post-process
  74738. this._createMotionBlurPostProcess(scene, ratio);
  74739. }
  74740. if (this._cameras !== null) {
  74741. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74742. }
  74743. };
  74744. // Down Sample X4 Post-Processs
  74745. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74746. var _this = this;
  74747. var downSampleX4Offsets = new Array(32);
  74748. 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);
  74749. this.downSampleX4PostProcess.onApply = function (effect) {
  74750. var id = 0;
  74751. var width = _this.downSampleX4PostProcess.width;
  74752. var height = _this.downSampleX4PostProcess.height;
  74753. for (var i = -2; i < 2; i++) {
  74754. for (var j = -2; j < 2; j++) {
  74755. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74756. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74757. id += 2;
  74758. }
  74759. }
  74760. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74761. };
  74762. // Add to pipeline
  74763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74764. };
  74765. // Brightpass Post-Process
  74766. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74767. var _this = this;
  74768. var brightOffsets = new Array(8);
  74769. 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);
  74770. this.brightPassPostProcess.onApply = function (effect) {
  74771. var sU = (1.0 / _this.brightPassPostProcess.width);
  74772. var sV = (1.0 / _this.brightPassPostProcess.height);
  74773. brightOffsets[0] = -0.5 * sU;
  74774. brightOffsets[1] = 0.5 * sV;
  74775. brightOffsets[2] = 0.5 * sU;
  74776. brightOffsets[3] = 0.5 * sV;
  74777. brightOffsets[4] = -0.5 * sU;
  74778. brightOffsets[5] = -0.5 * sV;
  74779. brightOffsets[6] = 0.5 * sU;
  74780. brightOffsets[7] = -0.5 * sV;
  74781. effect.setArray2("dsOffsets", brightOffsets);
  74782. effect.setFloat("brightThreshold", _this.brightThreshold);
  74783. };
  74784. // Add to pipeline
  74785. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74786. };
  74787. // Create blur H&V post-processes
  74788. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74789. var _this = this;
  74790. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74791. var engine = scene.getEngine();
  74792. 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);
  74793. 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);
  74794. blurX.onActivateObservable.add(function () {
  74795. var dw = blurX.width / engine.getRenderWidth();
  74796. blurX.kernel = _this[blurWidthKey] * dw;
  74797. });
  74798. blurY.onActivateObservable.add(function () {
  74799. var dw = blurY.height / engine.getRenderHeight();
  74800. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74801. });
  74802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74804. this.blurHPostProcesses.push(blurX);
  74805. this.blurVPostProcesses.push(blurY);
  74806. };
  74807. // Create texture adder post-process
  74808. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74809. var _this = this;
  74810. 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);
  74811. this.textureAdderPostProcess.onApply = function (effect) {
  74812. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74813. effect.setTexture("lensSampler", _this.lensTexture);
  74814. effect.setFloat("exposure", _this.exposure);
  74815. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74816. };
  74817. // Add to pipeline
  74818. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74819. };
  74820. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74821. var _this = this;
  74822. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74823. geometryRenderer.enablePosition = true;
  74824. var geometry = geometryRenderer.getGBuffer();
  74825. // Base post-process
  74826. 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));
  74827. var depthValues = BABYLON.Vector2.Zero();
  74828. this.volumetricLightPostProcess.onApply = function (effect) {
  74829. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74830. var generator = _this.sourceLight.getShadowGenerator();
  74831. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74832. effect.setTexture("positionSampler", geometry.textures[2]);
  74833. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74834. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74835. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74836. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74837. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74838. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74839. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74840. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74841. effect.setVector2("depthValues", depthValues);
  74842. }
  74843. };
  74844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74845. // Smooth
  74846. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74847. // Merge
  74848. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74849. this.volumetricLightMergePostProces.onApply = function (effect) {
  74850. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74851. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74852. };
  74853. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74854. };
  74855. // Create luminance
  74856. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74857. var _this = this;
  74858. // Create luminance
  74859. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74860. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74861. var offsets = [];
  74862. this.luminancePostProcess.onApply = function (effect) {
  74863. var sU = (1.0 / _this.luminancePostProcess.width);
  74864. var sV = (1.0 / _this.luminancePostProcess.height);
  74865. offsets[0] = -0.5 * sU;
  74866. offsets[1] = 0.5 * sV;
  74867. offsets[2] = 0.5 * sU;
  74868. offsets[3] = 0.5 * sV;
  74869. offsets[4] = -0.5 * sU;
  74870. offsets[5] = -0.5 * sV;
  74871. offsets[6] = 0.5 * sU;
  74872. offsets[7] = -0.5 * sV;
  74873. effect.setArray2("lumOffsets", offsets);
  74874. };
  74875. // Add to pipeline
  74876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74877. // Create down sample luminance
  74878. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74879. var size = Math.pow(3, i);
  74880. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74881. if (i === 0) {
  74882. defines += "#define FINAL_DOWN_SAMPLER";
  74883. }
  74884. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74885. this.luminanceDownSamplePostProcesses.push(postProcess);
  74886. }
  74887. // Create callbacks and add effects
  74888. var lastLuminance = this.luminancePostProcess;
  74889. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74890. var downSampleOffsets = new Array(18);
  74891. pp.onApply = function (effect) {
  74892. if (!lastLuminance) {
  74893. return;
  74894. }
  74895. var id = 0;
  74896. for (var x = -1; x < 2; x++) {
  74897. for (var y = -1; y < 2; y++) {
  74898. downSampleOffsets[id] = x / lastLuminance.width;
  74899. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74900. id += 2;
  74901. }
  74902. }
  74903. effect.setArray2("dsOffsets", downSampleOffsets);
  74904. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74905. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74906. lastLuminance = _this.luminancePostProcess;
  74907. }
  74908. else {
  74909. lastLuminance = pp;
  74910. }
  74911. };
  74912. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74913. pp.onAfterRender = function (effect) {
  74914. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74915. 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);
  74916. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74917. };
  74918. }
  74919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74920. });
  74921. };
  74922. // Create HDR post-process
  74923. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74924. var _this = this;
  74925. 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);
  74926. var outputLiminance = 1;
  74927. var time = 0;
  74928. var lastTime = 0;
  74929. this.hdrPostProcess.onApply = function (effect) {
  74930. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74931. time += scene.getEngine().getDeltaTime();
  74932. if (outputLiminance < 0) {
  74933. outputLiminance = _this._hdrCurrentLuminance;
  74934. }
  74935. else {
  74936. var dt = (lastTime - time) / 1000.0;
  74937. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74938. outputLiminance += _this.hdrDecreaseRate * dt;
  74939. }
  74940. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74941. outputLiminance -= _this.hdrIncreaseRate * dt;
  74942. }
  74943. else {
  74944. outputLiminance = _this._hdrCurrentLuminance;
  74945. }
  74946. }
  74947. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74948. effect.setFloat("averageLuminance", outputLiminance);
  74949. lastTime = time;
  74950. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74951. };
  74952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74953. };
  74954. // Create lens flare post-process
  74955. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74956. var _this = this;
  74957. 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);
  74958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74959. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74960. 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);
  74961. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74962. var resolution = new BABYLON.Vector2(0, 0);
  74963. // Lens flare
  74964. this.lensFlarePostProcess.onApply = function (effect) {
  74965. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74966. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74967. effect.setFloat("strength", _this.lensFlareStrength);
  74968. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74969. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74970. // Shift
  74971. resolution.x = _this.lensFlarePostProcess.width;
  74972. resolution.y = _this.lensFlarePostProcess.height;
  74973. effect.setVector2("resolution", resolution);
  74974. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74975. };
  74976. // Compose
  74977. 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);
  74978. 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);
  74979. this.lensFlareComposePostProcess.onApply = function (effect) {
  74980. if (!_this._scene.activeCamera) {
  74981. return;
  74982. }
  74983. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74984. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74985. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74986. // Lens start rotation matrix
  74987. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74988. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74989. 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));
  74990. camRot *= 4.0;
  74991. 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);
  74992. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74993. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74994. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74995. };
  74996. };
  74997. // Create depth-of-field post-process
  74998. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74999. var _this = this;
  75000. 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);
  75001. this.depthOfFieldPostProcess.onApply = function (effect) {
  75002. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75003. effect.setTexture("depthSampler", _this._getDepthTexture());
  75004. effect.setFloat("distance", _this.depthOfFieldDistance);
  75005. };
  75006. // Add to pipeline
  75007. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75008. };
  75009. // Create motion blur post-process
  75010. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75011. var _this = this;
  75012. 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);
  75013. var motionScale = 0;
  75014. var prevViewProjection = BABYLON.Matrix.Identity();
  75015. var invViewProjection = BABYLON.Matrix.Identity();
  75016. var viewProjection = BABYLON.Matrix.Identity();
  75017. var screenSize = BABYLON.Vector2.Zero();
  75018. this.motionBlurPostProcess.onApply = function (effect) {
  75019. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75020. viewProjection.invertToRef(invViewProjection);
  75021. effect.setMatrix("inverseViewProjection", invViewProjection);
  75022. effect.setMatrix("prevViewProjection", prevViewProjection);
  75023. prevViewProjection = viewProjection;
  75024. screenSize.x = _this.motionBlurPostProcess.width;
  75025. screenSize.y = _this.motionBlurPostProcess.height;
  75026. effect.setVector2("screenSize", screenSize);
  75027. motionScale = scene.getEngine().getFps() / 60.0;
  75028. effect.setFloat("motionScale", motionScale);
  75029. effect.setFloat("motionStrength", _this.motionStrength);
  75030. effect.setTexture("depthSampler", _this._getDepthTexture());
  75031. };
  75032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75033. };
  75034. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75035. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75036. var renderer = this._scene.enableGeometryBufferRenderer();
  75037. return renderer.getGBuffer().textures[0];
  75038. }
  75039. return this._scene.enableDepthRenderer().getDepthMap();
  75040. };
  75041. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75042. for (var i = 0; i < this._cameras.length; i++) {
  75043. var camera = this._cameras[i];
  75044. if (this.originalPostProcess) {
  75045. this.originalPostProcess.dispose(camera);
  75046. }
  75047. if (this.downSampleX4PostProcess) {
  75048. this.downSampleX4PostProcess.dispose(camera);
  75049. }
  75050. if (this.brightPassPostProcess) {
  75051. this.brightPassPostProcess.dispose(camera);
  75052. }
  75053. if (this.textureAdderPostProcess) {
  75054. this.textureAdderPostProcess.dispose(camera);
  75055. }
  75056. if (this.textureAdderFinalPostProcess) {
  75057. this.textureAdderFinalPostProcess.dispose(camera);
  75058. }
  75059. if (this.volumetricLightPostProcess) {
  75060. this.volumetricLightPostProcess.dispose(camera);
  75061. }
  75062. if (this.volumetricLightSmoothXPostProcess) {
  75063. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75064. }
  75065. if (this.volumetricLightSmoothYPostProcess) {
  75066. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75067. }
  75068. if (this.volumetricLightMergePostProces) {
  75069. this.volumetricLightMergePostProces.dispose(camera);
  75070. }
  75071. if (this.volumetricLightFinalPostProcess) {
  75072. this.volumetricLightFinalPostProcess.dispose(camera);
  75073. }
  75074. if (this.lensFlarePostProcess) {
  75075. this.lensFlarePostProcess.dispose(camera);
  75076. }
  75077. if (this.lensFlareComposePostProcess) {
  75078. this.lensFlareComposePostProcess.dispose(camera);
  75079. }
  75080. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75081. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75082. }
  75083. if (this.luminancePostProcess) {
  75084. this.luminancePostProcess.dispose(camera);
  75085. }
  75086. if (this.hdrPostProcess) {
  75087. this.hdrPostProcess.dispose(camera);
  75088. }
  75089. if (this.hdrFinalPostProcess) {
  75090. this.hdrFinalPostProcess.dispose(camera);
  75091. }
  75092. if (this.depthOfFieldPostProcess) {
  75093. this.depthOfFieldPostProcess.dispose(camera);
  75094. }
  75095. if (this.motionBlurPostProcess) {
  75096. this.motionBlurPostProcess.dispose(camera);
  75097. }
  75098. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75099. this.blurHPostProcesses[j].dispose(camera);
  75100. }
  75101. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75102. this.blurVPostProcesses[j].dispose(camera);
  75103. }
  75104. }
  75105. this.originalPostProcess = null;
  75106. this.downSampleX4PostProcess = null;
  75107. this.brightPassPostProcess = null;
  75108. this.textureAdderPostProcess = null;
  75109. this.textureAdderFinalPostProcess = null;
  75110. this.volumetricLightPostProcess = null;
  75111. this.volumetricLightSmoothXPostProcess = null;
  75112. this.volumetricLightSmoothYPostProcess = null;
  75113. this.volumetricLightMergePostProces = null;
  75114. this.volumetricLightFinalPostProcess = null;
  75115. this.lensFlarePostProcess = null;
  75116. this.lensFlareComposePostProcess = null;
  75117. this.luminancePostProcess = null;
  75118. this.hdrPostProcess = null;
  75119. this.hdrFinalPostProcess = null;
  75120. this.depthOfFieldPostProcess = null;
  75121. this.motionBlurPostProcess = null;
  75122. this.luminanceDownSamplePostProcesses = [];
  75123. this.blurHPostProcesses = [];
  75124. this.blurVPostProcesses = [];
  75125. };
  75126. /**
  75127. * Dispose of the pipeline and stop all post processes
  75128. */
  75129. StandardRenderingPipeline.prototype.dispose = function () {
  75130. this._disposePostProcesses();
  75131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75132. _super.prototype.dispose.call(this);
  75133. };
  75134. /**
  75135. * Serialize the rendering pipeline (Used when exporting)
  75136. * @returns the serialized object
  75137. */
  75138. StandardRenderingPipeline.prototype.serialize = function () {
  75139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75140. if (this.sourceLight) {
  75141. serializationObject.sourceLightId = this.sourceLight.id;
  75142. }
  75143. serializationObject.customType = "StandardRenderingPipeline";
  75144. return serializationObject;
  75145. };
  75146. /**
  75147. * Parse the serialized pipeline
  75148. * @param source Source pipeline.
  75149. * @param scene The scene to load the pipeline to.
  75150. * @param rootUrl The URL of the serialized pipeline.
  75151. * @returns An instantiated pipeline from the serialized object.
  75152. */
  75153. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75154. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75155. if (source.sourceLightId) {
  75156. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75157. }
  75158. return p;
  75159. };
  75160. // Luminance steps
  75161. StandardRenderingPipeline.LuminanceSteps = 6;
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75165. __decorate([
  75166. BABYLON.serialize()
  75167. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75168. __decorate([
  75169. BABYLON.serialize()
  75170. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75171. __decorate([
  75172. BABYLON.serialize()
  75173. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75174. __decorate([
  75175. BABYLON.serializeAsTexture("lensTexture")
  75176. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75177. __decorate([
  75178. BABYLON.serialize()
  75179. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75180. __decorate([
  75181. BABYLON.serialize()
  75182. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75183. __decorate([
  75184. BABYLON.serialize()
  75185. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75186. __decorate([
  75187. BABYLON.serialize()
  75188. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75195. __decorate([
  75196. BABYLON.serializeAsTexture("lensColorTexture")
  75197. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75204. __decorate([
  75205. BABYLON.serialize()
  75206. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75210. __decorate([
  75211. BABYLON.serializeAsTexture("lensStarTexture")
  75212. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75213. __decorate([
  75214. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75215. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75222. __decorate([
  75223. BABYLON.serialize()
  75224. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75231. __decorate([
  75232. BABYLON.serialize()
  75233. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75234. __decorate([
  75235. BABYLON.serialize()
  75236. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75237. __decorate([
  75238. BABYLON.serialize()
  75239. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75240. __decorate([
  75241. BABYLON.serialize()
  75242. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75243. __decorate([
  75244. BABYLON.serialize()
  75245. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75246. __decorate([
  75247. BABYLON.serialize()
  75248. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75249. __decorate([
  75250. BABYLON.serialize()
  75251. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75252. return StandardRenderingPipeline;
  75253. }(BABYLON.PostProcessRenderPipeline));
  75254. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75255. })(BABYLON || (BABYLON = {}));
  75256. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75257. var BABYLON;
  75258. (function (BABYLON) {
  75259. var FxaaPostProcess = /** @class */ (function (_super) {
  75260. __extends(FxaaPostProcess, _super);
  75261. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75262. if (camera === void 0) { camera = null; }
  75263. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75264. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75265. var defines = _this._getDefines();
  75266. _this.updateEffect(defines);
  75267. _this.onApplyObservable.add(function (effect) {
  75268. var texelSize = _this.texelSize;
  75269. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75270. });
  75271. return _this;
  75272. }
  75273. FxaaPostProcess.prototype._getDefines = function () {
  75274. var engine = this.getEngine();
  75275. if (!engine) {
  75276. return null;
  75277. }
  75278. var glInfo = engine.getGlInfo();
  75279. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75280. return "#define MALI 1\n";
  75281. }
  75282. return null;
  75283. };
  75284. return FxaaPostProcess;
  75285. }(BABYLON.PostProcess));
  75286. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75287. })(BABYLON || (BABYLON = {}));
  75288. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75289. var BABYLON;
  75290. (function (BABYLON) {
  75291. /**
  75292. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75293. */
  75294. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75295. __extends(ChromaticAberrationPostProcess, _super);
  75296. /**
  75297. * Creates a new instance ChromaticAberrationPostProcess
  75298. * @param name The name of the effect.
  75299. * @param screenWidth The width of the screen to apply the effect on.
  75300. * @param screenHeight The height of the screen to apply the effect on.
  75301. * @param options The required width/height ratio to downsize to before computing the render pass.
  75302. * @param camera The camera to apply the render pass to.
  75303. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75304. * @param engine The engine which the post process will be applied. (default: current engine)
  75305. * @param reusable If the post process can be reused on the same frame. (default: false)
  75306. * @param textureType Type of textures used when performing the post process. (default: 0)
  75307. * @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)
  75308. */
  75309. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75310. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75311. if (blockCompilation === void 0) { blockCompilation = false; }
  75312. 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;
  75313. /**
  75314. * The amount of seperation of rgb channels (default: 30)
  75315. */
  75316. _this.aberrationAmount = 30;
  75317. /**
  75318. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75319. */
  75320. _this.radialIntensity = 0;
  75321. /**
  75322. * 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))
  75323. */
  75324. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75325. /**
  75326. * 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))
  75327. */
  75328. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75329. _this.onApplyObservable.add(function (effect) {
  75330. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75331. effect.setFloat('screen_width', screenWidth);
  75332. effect.setFloat('screen_height', screenHeight);
  75333. effect.setFloat('radialIntensity', _this.radialIntensity);
  75334. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75335. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75336. });
  75337. return _this;
  75338. }
  75339. return ChromaticAberrationPostProcess;
  75340. }(BABYLON.PostProcess));
  75341. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75342. })(BABYLON || (BABYLON = {}));
  75343. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75344. var BABYLON;
  75345. (function (BABYLON) {
  75346. /**
  75347. * The GrainPostProcess adds noise to the image at mid luminance levels
  75348. */
  75349. var GrainPostProcess = /** @class */ (function (_super) {
  75350. __extends(GrainPostProcess, _super);
  75351. /**
  75352. * Creates a new instance of @see GrainPostProcess
  75353. * @param name The name of the effect.
  75354. * @param options The required width/height ratio to downsize to before computing the render pass.
  75355. * @param camera The camera to apply the render pass to.
  75356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75357. * @param engine The engine which the post process will be applied. (default: current engine)
  75358. * @param reusable If the post process can be reused on the same frame. (default: false)
  75359. * @param textureType Type of textures used when performing the post process. (default: 0)
  75360. * @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)
  75361. */
  75362. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75364. if (blockCompilation === void 0) { blockCompilation = false; }
  75365. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75366. /**
  75367. * The intensity of the grain added (default: 30)
  75368. */
  75369. _this.intensity = 30;
  75370. /**
  75371. * If the grain should be randomized on every frame
  75372. */
  75373. _this.animated = false;
  75374. _this.onApplyObservable.add(function (effect) {
  75375. effect.setFloat('intensity', _this.intensity);
  75376. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75377. });
  75378. return _this;
  75379. }
  75380. return GrainPostProcess;
  75381. }(BABYLON.PostProcess));
  75382. BABYLON.GrainPostProcess = GrainPostProcess;
  75383. })(BABYLON || (BABYLON = {}));
  75384. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75385. var BABYLON;
  75386. (function (BABYLON) {
  75387. /**
  75388. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75389. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75390. */
  75391. var SharpenPostProcess = /** @class */ (function (_super) {
  75392. __extends(SharpenPostProcess, _super);
  75393. /**
  75394. * Creates a new instance ConvolutionPostProcess
  75395. * @param name The name of the effect.
  75396. * @param options The required width/height ratio to downsize to before computing the render pass.
  75397. * @param camera The camera to apply the render pass to.
  75398. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75399. * @param engine The engine which the post process will be applied. (default: current engine)
  75400. * @param reusable If the post process can be reused on the same frame. (default: false)
  75401. * @param textureType Type of textures used when performing the post process. (default: 0)
  75402. * @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)
  75403. */
  75404. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75405. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75406. if (blockCompilation === void 0) { blockCompilation = false; }
  75407. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75408. /**
  75409. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75410. */
  75411. _this.colorAmount = 1.0;
  75412. /**
  75413. * How much sharpness should be applied (default: 0.3)
  75414. */
  75415. _this.edgeAmount = 0.3;
  75416. _this.onApply = function (effect) {
  75417. effect.setFloat2("screenSize", _this.width, _this.height);
  75418. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75419. };
  75420. return _this;
  75421. }
  75422. return SharpenPostProcess;
  75423. }(BABYLON.PostProcess));
  75424. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75425. })(BABYLON || (BABYLON = {}));
  75426. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75427. var BABYLON;
  75428. (function (BABYLON) {
  75429. /**
  75430. * The Blur Post Process which blurs an image based on a kernel and direction.
  75431. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75432. */
  75433. var BlurPostProcess = /** @class */ (function (_super) {
  75434. __extends(BlurPostProcess, _super);
  75435. /**
  75436. * Creates a new instance BlurPostProcess
  75437. * @param name The name of the effect.
  75438. * @param direction The direction in which to blur the image.
  75439. * @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.
  75440. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75441. * @param camera The camera to apply the render pass to.
  75442. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75443. * @param engine The engine which the post process will be applied. (default: current engine)
  75444. * @param reusable If the post process can be reused on the same frame. (default: false)
  75445. * @param textureType Type of textures used when performing the post process. (default: 0)
  75446. * @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)
  75447. */
  75448. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75450. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75451. if (defines === void 0) { defines = ""; }
  75452. if (blockCompilation === void 0) { blockCompilation = false; }
  75453. 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;
  75454. _this.direction = direction;
  75455. _this.blockCompilation = blockCompilation;
  75456. _this._packedFloat = false;
  75457. _this._staticDefines = "";
  75458. _this._staticDefines = defines;
  75459. _this.onApplyObservable.add(function (effect) {
  75460. if (_this._outputTexture) {
  75461. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75462. }
  75463. else {
  75464. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75465. }
  75466. });
  75467. _this.kernel = kernel;
  75468. return _this;
  75469. }
  75470. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75471. /**
  75472. * Gets the length in pixels of the blur sample region
  75473. */
  75474. get: function () {
  75475. return this._idealKernel;
  75476. },
  75477. /**
  75478. * Sets the length in pixels of the blur sample region
  75479. */
  75480. set: function (v) {
  75481. if (this._idealKernel === v) {
  75482. return;
  75483. }
  75484. v = Math.max(v, 1);
  75485. this._idealKernel = v;
  75486. this._kernel = this._nearestBestKernel(v);
  75487. if (!this.blockCompilation) {
  75488. this._updateParameters();
  75489. }
  75490. },
  75491. enumerable: true,
  75492. configurable: true
  75493. });
  75494. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75495. /**
  75496. * Gets wether or not the blur is unpacking/repacking floats
  75497. */
  75498. get: function () {
  75499. return this._packedFloat;
  75500. },
  75501. /**
  75502. * Sets wether or not the blur needs to unpack/repack floats
  75503. */
  75504. set: function (v) {
  75505. if (this._packedFloat === v) {
  75506. return;
  75507. }
  75508. this._packedFloat = v;
  75509. if (!this.blockCompilation) {
  75510. this._updateParameters();
  75511. }
  75512. },
  75513. enumerable: true,
  75514. configurable: true
  75515. });
  75516. /**
  75517. * Updates the effect with the current post process compile time values and recompiles the shader.
  75518. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75519. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75520. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75521. * @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
  75522. * @param onCompiled Called when the shader has been compiled.
  75523. * @param onError Called if there is an error when compiling a shader.
  75524. */
  75525. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75526. if (defines === void 0) { defines = null; }
  75527. if (uniforms === void 0) { uniforms = null; }
  75528. if (samplers === void 0) { samplers = null; }
  75529. this._updateParameters(onCompiled, onError);
  75530. };
  75531. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75532. // Generate sampling offsets and weights
  75533. var N = this._kernel;
  75534. var centerIndex = (N - 1) / 2;
  75535. // Generate Gaussian sampling weights over kernel
  75536. var offsets = [];
  75537. var weights = [];
  75538. var totalWeight = 0;
  75539. for (var i = 0; i < N; i++) {
  75540. var u = i / (N - 1);
  75541. var w = this._gaussianWeight(u * 2.0 - 1);
  75542. offsets[i] = (i - centerIndex);
  75543. weights[i] = w;
  75544. totalWeight += w;
  75545. }
  75546. // Normalize weights
  75547. for (var i = 0; i < weights.length; i++) {
  75548. weights[i] /= totalWeight;
  75549. }
  75550. // Optimize: combine samples to take advantage of hardware linear sampling
  75551. // Walk from left to center, combining pairs (symmetrically)
  75552. var linearSamplingWeights = [];
  75553. var linearSamplingOffsets = [];
  75554. var linearSamplingMap = [];
  75555. for (var i = 0; i <= centerIndex; i += 2) {
  75556. var j = Math.min(i + 1, Math.floor(centerIndex));
  75557. var singleCenterSample = i === j;
  75558. if (singleCenterSample) {
  75559. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75560. }
  75561. else {
  75562. var sharedCell = j === centerIndex;
  75563. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75564. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75565. if (offsetLinear === 0) {
  75566. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75567. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75568. }
  75569. else {
  75570. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75571. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75572. }
  75573. }
  75574. }
  75575. for (var i = 0; i < linearSamplingMap.length; i++) {
  75576. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75577. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75578. }
  75579. // Replace with optimized
  75580. offsets = linearSamplingOffsets;
  75581. weights = linearSamplingWeights;
  75582. // Generate shaders
  75583. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75584. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75585. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75586. var defines = "";
  75587. defines += this._staticDefines;
  75588. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75589. if (this._staticDefines.indexOf("DOF") != -1) {
  75590. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75591. varyingCount--;
  75592. }
  75593. for (var i = 0; i < varyingCount; i++) {
  75594. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75595. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75596. }
  75597. var depCount = 0;
  75598. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75599. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75600. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75601. depCount++;
  75602. }
  75603. if (this.packedFloat) {
  75604. defines += "#define PACKEDFLOAT 1";
  75605. }
  75606. this.blockCompilation = false;
  75607. _super.prototype.updateEffect.call(this, defines, null, null, {
  75608. varyingCount: varyingCount,
  75609. depCount: depCount
  75610. }, onCompiled, onError);
  75611. };
  75612. /**
  75613. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75614. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75615. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75616. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75617. * The gaps between physical kernels are compensated for in the weighting of the samples
  75618. * @param idealKernel Ideal blur kernel.
  75619. * @return Nearest best kernel.
  75620. */
  75621. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75622. var v = Math.round(idealKernel);
  75623. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75624. var k = _a[_i];
  75625. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75626. return Math.max(k, 3);
  75627. }
  75628. }
  75629. return Math.max(v, 3);
  75630. };
  75631. /**
  75632. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75633. * @param x The point on the Gaussian distribution to sample.
  75634. * @return the value of the Gaussian function at x.
  75635. */
  75636. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75637. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75638. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75639. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75640. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75641. // truncated at around 1.3% of peak strength.
  75642. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75643. var sigma = (1 / 3);
  75644. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75645. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75646. var weight = (1.0 / denominator) * Math.exp(exponent);
  75647. return weight;
  75648. };
  75649. /**
  75650. * Generates a string that can be used as a floating point number in GLSL.
  75651. * @param x Value to print.
  75652. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75653. * @return GLSL float string.
  75654. */
  75655. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75656. if (decimalFigures === void 0) { decimalFigures = 8; }
  75657. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75658. };
  75659. return BlurPostProcess;
  75660. }(BABYLON.PostProcess));
  75661. BABYLON.BlurPostProcess = BlurPostProcess;
  75662. })(BABYLON || (BABYLON = {}));
  75663. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75664. var BABYLON;
  75665. (function (BABYLON) {
  75666. /**
  75667. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75668. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75669. * based on samples that have a large difference in distance than the center pixel.
  75670. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75671. */
  75672. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75673. __extends(DepthOfFieldBlurPostProcess, _super);
  75674. /**
  75675. * Creates a new instance CircleOfConfusionPostProcess
  75676. * @param name The name of the effect.
  75677. * @param scene The scene the effect belongs to.
  75678. * @param direction The direction the blur should be applied.
  75679. * @param kernel The size of the kernel used to blur.
  75680. * @param options The required width/height ratio to downsize to before computing the render pass.
  75681. * @param camera The camera to apply the render pass to.
  75682. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75683. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75684. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75685. * @param engine The engine which the post process will be applied. (default: current engine)
  75686. * @param reusable If the post process can be reused on the same frame. (default: false)
  75687. * @param textureType Type of textures used when performing the post process. (default: 0)
  75688. * @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)
  75689. */
  75690. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75691. if (imageToBlur === void 0) { imageToBlur = null; }
  75692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75693. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75694. if (blockCompilation === void 0) { blockCompilation = false; }
  75695. 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;
  75696. _this.direction = direction;
  75697. _this.onApplyObservable.add(function (effect) {
  75698. if (imageToBlur != null) {
  75699. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75700. }
  75701. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75702. if (scene.activeCamera) {
  75703. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75704. }
  75705. });
  75706. return _this;
  75707. }
  75708. return DepthOfFieldBlurPostProcess;
  75709. }(BABYLON.BlurPostProcess));
  75710. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75711. })(BABYLON || (BABYLON = {}));
  75712. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75713. var BABYLON;
  75714. (function (BABYLON) {
  75715. /**
  75716. * Options to be set when merging outputs from the default pipeline.
  75717. */
  75718. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75719. function DepthOfFieldMergePostProcessOptions() {
  75720. }
  75721. return DepthOfFieldMergePostProcessOptions;
  75722. }());
  75723. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75724. /**
  75725. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75726. */
  75727. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75728. __extends(DepthOfFieldMergePostProcess, _super);
  75729. /**
  75730. * Creates a new instance of DepthOfFieldMergePostProcess
  75731. * @param name The name of the effect.
  75732. * @param originalFromInput Post process which's input will be used for the merge.
  75733. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75734. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75735. * @param options The required width/height ratio to downsize to before computing the render pass.
  75736. * @param camera The camera to apply the render pass to.
  75737. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75738. * @param engine The engine which the post process will be applied. (default: current engine)
  75739. * @param reusable If the post process can be reused on the same frame. (default: false)
  75740. * @param textureType Type of textures used when performing the post process. (default: 0)
  75741. * @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)
  75742. */
  75743. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75744. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75745. if (blockCompilation === void 0) { blockCompilation = false; }
  75746. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75747. _this.blurSteps = blurSteps;
  75748. _this.onApplyObservable.add(function (effect) {
  75749. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75750. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75751. blurSteps.forEach(function (step, index) {
  75752. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75753. });
  75754. });
  75755. if (!blockCompilation) {
  75756. _this.updateEffect();
  75757. }
  75758. return _this;
  75759. }
  75760. /**
  75761. * Updates the effect with the current post process compile time values and recompiles the shader.
  75762. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75763. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75764. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75765. * @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
  75766. * @param onCompiled Called when the shader has been compiled.
  75767. * @param onError Called if there is an error when compiling a shader.
  75768. */
  75769. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75770. if (defines === void 0) { defines = null; }
  75771. if (uniforms === void 0) { uniforms = null; }
  75772. if (samplers === void 0) { samplers = null; }
  75773. if (!defines) {
  75774. defines = "";
  75775. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75776. }
  75777. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75778. };
  75779. return DepthOfFieldMergePostProcess;
  75780. }(BABYLON.PostProcess));
  75781. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75782. })(BABYLON || (BABYLON = {}));
  75783. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75784. var BABYLON;
  75785. (function (BABYLON) {
  75786. /**
  75787. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75788. */
  75789. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75790. __extends(CircleOfConfusionPostProcess, _super);
  75791. /**
  75792. * Creates a new instance CircleOfConfusionPostProcess
  75793. * @param name The name of the effect.
  75794. * @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.
  75795. * @param options The required width/height ratio to downsize to before computing the render pass.
  75796. * @param camera The camera to apply the render pass to.
  75797. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75798. * @param engine The engine which the post process will be applied. (default: current engine)
  75799. * @param reusable If the post process can be reused on the same frame. (default: false)
  75800. * @param textureType Type of textures used when performing the post process. (default: 0)
  75801. * @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)
  75802. */
  75803. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75804. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75805. if (blockCompilation === void 0) { blockCompilation = false; }
  75806. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75807. /**
  75808. * 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.
  75809. */
  75810. _this.lensSize = 50;
  75811. /**
  75812. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75813. */
  75814. _this.fStop = 1.4;
  75815. /**
  75816. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75817. */
  75818. _this.focusDistance = 2000;
  75819. /**
  75820. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75821. */
  75822. _this.focalLength = 50;
  75823. _this._depthTexture = null;
  75824. _this._depthTexture = depthTexture;
  75825. _this.onApplyObservable.add(function (effect) {
  75826. if (!_this._depthTexture) {
  75827. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75828. return;
  75829. }
  75830. effect.setTexture("depthSampler", _this._depthTexture);
  75831. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75832. var aperture = _this.lensSize / _this.fStop;
  75833. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75834. effect.setFloat('focusDistance', _this.focusDistance);
  75835. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75836. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75837. });
  75838. return _this;
  75839. }
  75840. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75841. /**
  75842. * 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.
  75843. */
  75844. set: function (value) {
  75845. this._depthTexture = value;
  75846. },
  75847. enumerable: true,
  75848. configurable: true
  75849. });
  75850. return CircleOfConfusionPostProcess;
  75851. }(BABYLON.PostProcess));
  75852. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75853. })(BABYLON || (BABYLON = {}));
  75854. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75855. var BABYLON;
  75856. (function (BABYLON) {
  75857. /**
  75858. * Specifies the level of max blur that should be applied when using the depth of field effect
  75859. */
  75860. var DepthOfFieldEffectBlurLevel;
  75861. (function (DepthOfFieldEffectBlurLevel) {
  75862. /**
  75863. * Subtle blur
  75864. */
  75865. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75866. /**
  75867. * Medium blur
  75868. */
  75869. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75870. /**
  75871. * Large blur
  75872. */
  75873. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75874. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75875. ;
  75876. /**
  75877. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75878. */
  75879. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75880. __extends(DepthOfFieldEffect, _super);
  75881. /**
  75882. * Creates a new instance DepthOfFieldEffect
  75883. * @param scene The scene the effect belongs to.
  75884. * @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.
  75885. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75886. * @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)
  75887. */
  75888. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75889. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75890. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75891. if (blockCompilation === void 0) { blockCompilation = false; }
  75892. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75893. return _this._effects;
  75894. }, true) || this;
  75895. /**
  75896. * Internal post processes in depth of field effect
  75897. */
  75898. _this._effects = [];
  75899. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75900. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75901. // 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)
  75902. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75903. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75904. _this._depthOfFieldBlurY = [];
  75905. _this._depthOfFieldBlurX = [];
  75906. var blurCount = 1;
  75907. var kernelSize = 15;
  75908. switch (blurLevel) {
  75909. case DepthOfFieldEffectBlurLevel.High: {
  75910. blurCount = 3;
  75911. kernelSize = 51;
  75912. break;
  75913. }
  75914. case DepthOfFieldEffectBlurLevel.Medium: {
  75915. blurCount = 2;
  75916. kernelSize = 31;
  75917. break;
  75918. }
  75919. default: {
  75920. kernelSize = 15;
  75921. blurCount = 1;
  75922. break;
  75923. }
  75924. }
  75925. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75926. var ratio = 1.0;
  75927. for (var i = 0; i < blurCount; i++) {
  75928. 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);
  75929. blurY.autoClear = false;
  75930. ratio = 0.75 / Math.pow(2, i);
  75931. 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);
  75932. blurX.autoClear = false;
  75933. _this._depthOfFieldBlurY.push(blurY);
  75934. _this._depthOfFieldBlurX.push(blurX);
  75935. }
  75936. // Set all post processes on the effect.
  75937. _this._effects = [_this._circleOfConfusion];
  75938. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75939. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75940. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75941. }
  75942. // Merge blurred images with original image based on circleOfConfusion
  75943. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75944. _this._dofMerge.autoClear = false;
  75945. _this._effects.push(_this._dofMerge);
  75946. return _this;
  75947. }
  75948. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75949. get: function () {
  75950. return this._circleOfConfusion.focalLength;
  75951. },
  75952. /**
  75953. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75954. */
  75955. set: function (value) {
  75956. this._circleOfConfusion.focalLength = value;
  75957. },
  75958. enumerable: true,
  75959. configurable: true
  75960. });
  75961. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75962. get: function () {
  75963. return this._circleOfConfusion.fStop;
  75964. },
  75965. /**
  75966. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75967. */
  75968. set: function (value) {
  75969. this._circleOfConfusion.fStop = value;
  75970. },
  75971. enumerable: true,
  75972. configurable: true
  75973. });
  75974. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75975. get: function () {
  75976. return this._circleOfConfusion.focusDistance;
  75977. },
  75978. /**
  75979. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75980. */
  75981. set: function (value) {
  75982. this._circleOfConfusion.focusDistance = value;
  75983. },
  75984. enumerable: true,
  75985. configurable: true
  75986. });
  75987. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75988. get: function () {
  75989. return this._circleOfConfusion.lensSize;
  75990. },
  75991. /**
  75992. * 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.
  75993. */
  75994. set: function (value) {
  75995. this._circleOfConfusion.lensSize = value;
  75996. },
  75997. enumerable: true,
  75998. configurable: true
  75999. });
  76000. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76001. /**
  76002. * 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.
  76003. */
  76004. set: function (value) {
  76005. this._circleOfConfusion.depthTexture = value;
  76006. },
  76007. enumerable: true,
  76008. configurable: true
  76009. });
  76010. /**
  76011. * Disposes each of the internal effects for a given camera.
  76012. * @param camera The camera to dispose the effect on.
  76013. */
  76014. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76015. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76016. this._effects[effectIndex].dispose(camera);
  76017. }
  76018. };
  76019. /**
  76020. * Internal
  76021. */
  76022. DepthOfFieldEffect.prototype._updateEffects = function () {
  76023. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76024. this._effects[effectIndex].updateEffect();
  76025. }
  76026. };
  76027. /**
  76028. * Internal
  76029. * @returns if all the contained post processes are ready.
  76030. */
  76031. DepthOfFieldEffect.prototype._isReady = function () {
  76032. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76033. if (!this._effects[effectIndex].isReady()) {
  76034. return false;
  76035. }
  76036. }
  76037. return true;
  76038. };
  76039. return DepthOfFieldEffect;
  76040. }(BABYLON.PostProcessRenderEffect));
  76041. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76042. })(BABYLON || (BABYLON = {}));
  76043. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76044. var BABYLON;
  76045. (function (BABYLON) {
  76046. /**
  76047. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76048. */
  76049. var BloomMergePostProcess = /** @class */ (function (_super) {
  76050. __extends(BloomMergePostProcess, _super);
  76051. /**
  76052. * Creates a new instance of @see BloomMergePostProcess
  76053. * @param name The name of the effect.
  76054. * @param originalFromInput Post process which's input will be used for the merge.
  76055. * @param blurred Blurred highlights post process which's output will be used.
  76056. * @param weight Weight of the bloom to be added to the original input.
  76057. * @param options The required width/height ratio to downsize to before computing the render pass.
  76058. * @param camera The camera to apply the render pass to.
  76059. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76060. * @param engine The engine which the post process will be applied. (default: current engine)
  76061. * @param reusable If the post process can be reused on the same frame. (default: false)
  76062. * @param textureType Type of textures used when performing the post process. (default: 0)
  76063. * @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)
  76064. */
  76065. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76066. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76067. if (blockCompilation === void 0) { blockCompilation = false; }
  76068. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76069. _this.weight = weight;
  76070. _this.onApplyObservable.add(function (effect) {
  76071. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76072. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76073. effect.setFloat("bloomWeight", _this.weight);
  76074. });
  76075. if (!blockCompilation) {
  76076. _this.updateEffect();
  76077. }
  76078. return _this;
  76079. }
  76080. return BloomMergePostProcess;
  76081. }(BABYLON.PostProcess));
  76082. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76083. })(BABYLON || (BABYLON = {}));
  76084. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76085. var BABYLON;
  76086. (function (BABYLON) {
  76087. /**
  76088. * 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.
  76089. */
  76090. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76091. __extends(ExtractHighlightsPostProcess, _super);
  76092. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76093. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76094. if (blockCompilation === void 0) { blockCompilation = false; }
  76095. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76096. /**
  76097. * The luminance threshold, pixels below this value will be set to black.
  76098. */
  76099. _this.threshold = 0.9;
  76100. /**
  76101. * Internal
  76102. */
  76103. _this._exposure = 1;
  76104. /**
  76105. * Post process which has the input texture to be used when performing highlight extraction
  76106. */
  76107. _this._inputPostProcess = null;
  76108. _this.onApplyObservable.add(function (effect) {
  76109. if (_this._inputPostProcess) {
  76110. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76111. }
  76112. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76113. effect.setFloat('exposure', _this._exposure);
  76114. });
  76115. return _this;
  76116. }
  76117. return ExtractHighlightsPostProcess;
  76118. }(BABYLON.PostProcess));
  76119. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76120. })(BABYLON || (BABYLON = {}));
  76121. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76122. var BABYLON;
  76123. (function (BABYLON) {
  76124. /**
  76125. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76126. */
  76127. var BloomEffect = /** @class */ (function (_super) {
  76128. __extends(BloomEffect, _super);
  76129. /**
  76130. * Creates a new instance of @see BloomEffect
  76131. * @param scene The scene the effect belongs to.
  76132. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76133. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76134. * @param bloomWeight The the strength of bloom.
  76135. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76136. * @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)
  76137. */
  76138. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76139. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76140. if (blockCompilation === void 0) { blockCompilation = false; }
  76141. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76142. return _this._effects;
  76143. }, true) || this;
  76144. _this.bloomScale = bloomScale;
  76145. /**
  76146. * Internal
  76147. */
  76148. _this._effects = [];
  76149. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76150. _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);
  76151. _this._blurX.alwaysForcePOT = true;
  76152. _this._blurX.autoClear = false;
  76153. _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);
  76154. _this._blurY.alwaysForcePOT = true;
  76155. _this._blurY.autoClear = false;
  76156. _this.kernel = bloomKernel;
  76157. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76158. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76159. _this._merge.autoClear = false;
  76160. _this._effects.push(_this._merge);
  76161. return _this;
  76162. }
  76163. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76164. /**
  76165. * The luminance threshold to find bright areas of the image to bloom.
  76166. */
  76167. get: function () {
  76168. return this._downscale.threshold;
  76169. },
  76170. set: function (value) {
  76171. this._downscale.threshold = value;
  76172. },
  76173. enumerable: true,
  76174. configurable: true
  76175. });
  76176. Object.defineProperty(BloomEffect.prototype, "weight", {
  76177. /**
  76178. * The strength of the bloom.
  76179. */
  76180. get: function () {
  76181. return this._merge.weight;
  76182. },
  76183. set: function (value) {
  76184. this._merge.weight = value;
  76185. },
  76186. enumerable: true,
  76187. configurable: true
  76188. });
  76189. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76190. /**
  76191. * Specifies the size of the bloom blur kernel, relative to the final output size
  76192. */
  76193. get: function () {
  76194. return this._blurX.kernel / this.bloomScale;
  76195. },
  76196. set: function (value) {
  76197. this._blurX.kernel = value * this.bloomScale;
  76198. this._blurY.kernel = value * this.bloomScale;
  76199. },
  76200. enumerable: true,
  76201. configurable: true
  76202. });
  76203. /**
  76204. * Disposes each of the internal effects for a given camera.
  76205. * @param camera The camera to dispose the effect on.
  76206. */
  76207. BloomEffect.prototype.disposeEffects = function (camera) {
  76208. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76209. this._effects[effectIndex].dispose(camera);
  76210. }
  76211. };
  76212. /**
  76213. * Internal
  76214. */
  76215. BloomEffect.prototype._updateEffects = function () {
  76216. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76217. this._effects[effectIndex].updateEffect();
  76218. }
  76219. };
  76220. /**
  76221. * Internal
  76222. * @returns if all the contained post processes are ready.
  76223. */
  76224. BloomEffect.prototype._isReady = function () {
  76225. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76226. if (!this._effects[effectIndex].isReady()) {
  76227. return false;
  76228. }
  76229. }
  76230. return true;
  76231. };
  76232. return BloomEffect;
  76233. }(BABYLON.PostProcessRenderEffect));
  76234. BABYLON.BloomEffect = BloomEffect;
  76235. })(BABYLON || (BABYLON = {}));
  76236. //# sourceMappingURL=babylon.bloomEffect.js.map
  76237. var BABYLON;
  76238. (function (BABYLON) {
  76239. /**
  76240. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76241. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76242. */
  76243. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76244. __extends(DefaultRenderingPipeline, _super);
  76245. /**
  76246. * @constructor
  76247. * @param {string} name - The rendering pipeline name (default: "")
  76248. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76249. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76250. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76251. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76252. */
  76253. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76254. if (name === void 0) { name = ""; }
  76255. if (hdr === void 0) { hdr = true; }
  76256. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76257. if (automaticBuild === void 0) { automaticBuild = true; }
  76258. var _this = _super.call(this, scene.getEngine(), name) || this;
  76259. _this._camerasToBeAttached = [];
  76260. /**
  76261. * ID of the sharpen post process,
  76262. */
  76263. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76264. /**
  76265. * ID of the image processing post process;
  76266. */
  76267. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76268. /**
  76269. * ID of the Fast Approximate Anti-Aliasing post process;
  76270. */
  76271. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76272. /**
  76273. * ID of the chromatic aberration post process,
  76274. */
  76275. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76276. /**
  76277. * ID of the grain post process
  76278. */
  76279. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76280. /**
  76281. * Glow post process which adds a glow to emmisive areas of the image
  76282. */
  76283. _this._glowLayer = null;
  76284. /**
  76285. * Animations which can be used to tweak settings over a period of time
  76286. */
  76287. _this.animations = [];
  76288. _this._imageProcessingConfigurationObserver = null;
  76289. // Values
  76290. _this._sharpenEnabled = false;
  76291. _this._bloomEnabled = false;
  76292. _this._depthOfFieldEnabled = false;
  76293. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76294. _this._fxaaEnabled = false;
  76295. _this._imageProcessingEnabled = true;
  76296. _this._bloomScale = 0.5;
  76297. _this._chromaticAberrationEnabled = false;
  76298. _this._grainEnabled = false;
  76299. _this._buildAllowed = true;
  76300. _this._resizeObserver = null;
  76301. _this._hardwareScaleLevel = 1.0;
  76302. _this._bloomKernel = 64;
  76303. /**
  76304. * Specifies the weight of the bloom in the final rendering
  76305. */
  76306. _this._bloomWeight = 0.15;
  76307. /**
  76308. * Specifies the luma threshold for the area that will be blurred by the bloom
  76309. */
  76310. _this._bloomThreshold = 0.9;
  76311. _this._samples = 1;
  76312. _this._hasCleared = false;
  76313. _this._prevPostProcess = null;
  76314. _this._prevPrevPostProcess = null;
  76315. _this._cameras = cameras || scene.cameras;
  76316. _this._camerasToBeAttached = _this._cameras.slice();
  76317. _this._buildAllowed = automaticBuild;
  76318. // Initialize
  76319. _this._scene = scene;
  76320. var caps = _this._scene.getEngine().getCaps();
  76321. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76322. // Misc
  76323. if (_this._hdr) {
  76324. if (caps.textureHalfFloatRender) {
  76325. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76326. }
  76327. else if (caps.textureFloatRender) {
  76328. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76329. }
  76330. }
  76331. else {
  76332. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76333. }
  76334. // Attach
  76335. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76336. var engine = _this._scene.getEngine();
  76337. // Create post processes before hand so they can be modified before enabled.
  76338. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76339. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76340. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76341. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76342. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76343. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76344. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76345. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76346. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76347. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76348. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76349. _this.bloomKernel = _this.bloomKernel;
  76350. });
  76351. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76352. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76353. });
  76354. _this._buildPipeline();
  76355. return _this;
  76356. }
  76357. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76358. get: function () {
  76359. return this._sharpenEnabled;
  76360. },
  76361. /**
  76362. * Enable or disable the sharpen process from the pipeline
  76363. */
  76364. set: function (enabled) {
  76365. if (this._sharpenEnabled === enabled) {
  76366. return;
  76367. }
  76368. this._sharpenEnabled = enabled;
  76369. this._buildPipeline();
  76370. },
  76371. enumerable: true,
  76372. configurable: true
  76373. });
  76374. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76375. /**
  76376. * Specifies the size of the bloom blur kernel, relative to the final output size
  76377. */
  76378. get: function () {
  76379. return this._bloomKernel;
  76380. },
  76381. set: function (value) {
  76382. this._bloomKernel = value;
  76383. this.bloom.kernel = value / this._hardwareScaleLevel;
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76389. get: function () {
  76390. return this._bloomWeight;
  76391. },
  76392. /**
  76393. * The strength of the bloom.
  76394. */
  76395. set: function (value) {
  76396. if (this._bloomWeight === value) {
  76397. return;
  76398. }
  76399. this.bloom.weight = value;
  76400. this._bloomWeight = value;
  76401. },
  76402. enumerable: true,
  76403. configurable: true
  76404. });
  76405. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76406. get: function () {
  76407. return this._bloomThreshold;
  76408. },
  76409. /**
  76410. * The strength of the bloom.
  76411. */
  76412. set: function (value) {
  76413. if (this._bloomThreshold === value) {
  76414. return;
  76415. }
  76416. this.bloom.threshold = value;
  76417. this._bloomThreshold = value;
  76418. },
  76419. enumerable: true,
  76420. configurable: true
  76421. });
  76422. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76423. get: function () {
  76424. return this._bloomScale;
  76425. },
  76426. /**
  76427. * The scale of the bloom, lower value will provide better performance.
  76428. */
  76429. set: function (value) {
  76430. if (this._bloomScale === value) {
  76431. return;
  76432. }
  76433. this._bloomScale = value;
  76434. // recreate bloom and dispose old as this setting is not dynamic
  76435. this._rebuildBloom();
  76436. this._buildPipeline();
  76437. },
  76438. enumerable: true,
  76439. configurable: true
  76440. });
  76441. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76442. get: function () {
  76443. return this._bloomEnabled;
  76444. },
  76445. /**
  76446. * Enable or disable the bloom from the pipeline
  76447. */
  76448. set: function (enabled) {
  76449. if (this._bloomEnabled === enabled) {
  76450. return;
  76451. }
  76452. this._bloomEnabled = enabled;
  76453. this._buildPipeline();
  76454. },
  76455. enumerable: true,
  76456. configurable: true
  76457. });
  76458. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76459. // recreate bloom and dispose old as this setting is not dynamic
  76460. var oldBloom = this.bloom;
  76461. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76462. this.bloom.threshold = oldBloom.threshold;
  76463. for (var i = 0; i < this._cameras.length; i++) {
  76464. oldBloom.disposeEffects(this._cameras[i]);
  76465. }
  76466. };
  76467. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76468. /**
  76469. * If the depth of field is enabled.
  76470. */
  76471. get: function () {
  76472. return this._depthOfFieldEnabled;
  76473. },
  76474. set: function (enabled) {
  76475. if (this._depthOfFieldEnabled === enabled) {
  76476. return;
  76477. }
  76478. this._depthOfFieldEnabled = enabled;
  76479. this._buildPipeline();
  76480. },
  76481. enumerable: true,
  76482. configurable: true
  76483. });
  76484. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76485. /**
  76486. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76487. */
  76488. get: function () {
  76489. return this._depthOfFieldBlurLevel;
  76490. },
  76491. set: function (value) {
  76492. if (this._depthOfFieldBlurLevel === value) {
  76493. return;
  76494. }
  76495. this._depthOfFieldBlurLevel = value;
  76496. // recreate dof and dispose old as this setting is not dynamic
  76497. var oldDof = this.depthOfField;
  76498. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76499. this.depthOfField.focalLength = oldDof.focalLength;
  76500. this.depthOfField.focusDistance = oldDof.focusDistance;
  76501. this.depthOfField.fStop = oldDof.fStop;
  76502. this.depthOfField.lensSize = oldDof.lensSize;
  76503. for (var i = 0; i < this._cameras.length; i++) {
  76504. oldDof.disposeEffects(this._cameras[i]);
  76505. }
  76506. this._buildPipeline();
  76507. },
  76508. enumerable: true,
  76509. configurable: true
  76510. });
  76511. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76512. get: function () {
  76513. return this._fxaaEnabled;
  76514. },
  76515. /**
  76516. * If the anti aliasing is enabled.
  76517. */
  76518. set: function (enabled) {
  76519. if (this._fxaaEnabled === enabled) {
  76520. return;
  76521. }
  76522. this._fxaaEnabled = enabled;
  76523. this._buildPipeline();
  76524. },
  76525. enumerable: true,
  76526. configurable: true
  76527. });
  76528. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76529. get: function () {
  76530. return this._samples;
  76531. },
  76532. /**
  76533. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76534. */
  76535. set: function (sampleCount) {
  76536. if (this._samples === sampleCount) {
  76537. return;
  76538. }
  76539. this._samples = sampleCount;
  76540. this._buildPipeline();
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76546. get: function () {
  76547. return this._imageProcessingEnabled;
  76548. },
  76549. /**
  76550. * If image processing is enabled.
  76551. */
  76552. set: function (enabled) {
  76553. if (this._imageProcessingEnabled === enabled) {
  76554. return;
  76555. }
  76556. this._imageProcessingEnabled = enabled;
  76557. this._buildPipeline();
  76558. },
  76559. enumerable: true,
  76560. configurable: true
  76561. });
  76562. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76563. get: function () {
  76564. return this._glowLayer == null;
  76565. },
  76566. /**
  76567. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76568. */
  76569. set: function (enabled) {
  76570. if (enabled && !this._glowLayer) {
  76571. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76572. }
  76573. else if (!enabled && this._glowLayer) {
  76574. this._glowLayer.dispose();
  76575. this._glowLayer = null;
  76576. }
  76577. },
  76578. enumerable: true,
  76579. configurable: true
  76580. });
  76581. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76582. get: function () {
  76583. return this._chromaticAberrationEnabled;
  76584. },
  76585. /**
  76586. * Enable or disable the chromaticAberration process from the pipeline
  76587. */
  76588. set: function (enabled) {
  76589. if (this._chromaticAberrationEnabled === enabled) {
  76590. return;
  76591. }
  76592. this._chromaticAberrationEnabled = enabled;
  76593. this._buildPipeline();
  76594. },
  76595. enumerable: true,
  76596. configurable: true
  76597. });
  76598. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76599. get: function () {
  76600. return this._grainEnabled;
  76601. },
  76602. /**
  76603. * Enable or disable the grain process from the pipeline
  76604. */
  76605. set: function (enabled) {
  76606. if (this._grainEnabled === enabled) {
  76607. return;
  76608. }
  76609. this._grainEnabled = enabled;
  76610. this._buildPipeline();
  76611. },
  76612. enumerable: true,
  76613. configurable: true
  76614. });
  76615. /**
  76616. * Force the compilation of the entire pipeline.
  76617. */
  76618. DefaultRenderingPipeline.prototype.prepare = function () {
  76619. var previousState = this._buildAllowed;
  76620. this._buildAllowed = true;
  76621. this._buildPipeline();
  76622. this._buildAllowed = previousState;
  76623. };
  76624. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76625. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76626. if (this._hasCleared) {
  76627. postProcess.autoClear = false;
  76628. }
  76629. else {
  76630. postProcess.autoClear = true;
  76631. this._scene.autoClear = false;
  76632. this._hasCleared = true;
  76633. }
  76634. if (!skipTextureSharing) {
  76635. if (this._prevPrevPostProcess) {
  76636. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76637. }
  76638. else {
  76639. postProcess.useOwnOutput();
  76640. }
  76641. if (this._prevPostProcess) {
  76642. this._prevPrevPostProcess = this._prevPostProcess;
  76643. }
  76644. this._prevPostProcess = postProcess;
  76645. }
  76646. };
  76647. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76648. var _this = this;
  76649. if (!this._buildAllowed) {
  76650. return;
  76651. }
  76652. this._scene.autoClear = true;
  76653. var engine = this._scene.getEngine();
  76654. this._disposePostProcesses();
  76655. if (this._cameras !== null) {
  76656. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76657. // get back cameras to be used to reattach pipeline
  76658. this._cameras = this._camerasToBeAttached.slice();
  76659. }
  76660. this._reset();
  76661. this._prevPostProcess = null;
  76662. this._prevPrevPostProcess = null;
  76663. this._hasCleared = false;
  76664. if (this.depthOfFieldEnabled) {
  76665. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76666. this.depthOfField.depthTexture = depthTexture;
  76667. if (!this.depthOfField._isReady()) {
  76668. this.depthOfField._updateEffects();
  76669. }
  76670. this.addEffect(this.depthOfField);
  76671. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76672. }
  76673. if (this.bloomEnabled) {
  76674. if (!this.bloom._isReady()) {
  76675. this.bloom._updateEffects();
  76676. }
  76677. this.addEffect(this.bloom);
  76678. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76679. }
  76680. if (this._imageProcessingEnabled) {
  76681. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76682. if (this._hdr) {
  76683. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76684. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76685. }
  76686. else {
  76687. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76688. }
  76689. }
  76690. if (this.sharpenEnabled) {
  76691. if (!this.sharpen.isReady()) {
  76692. this.sharpen.updateEffect();
  76693. }
  76694. this.addEffect(this._sharpenEffect);
  76695. this._setAutoClearAndTextureSharing(this.sharpen);
  76696. }
  76697. if (this.grainEnabled) {
  76698. if (!this.grain.isReady()) {
  76699. this.grain.updateEffect();
  76700. }
  76701. this.addEffect(this._grainEffect);
  76702. this._setAutoClearAndTextureSharing(this.grain);
  76703. }
  76704. if (this.chromaticAberrationEnabled) {
  76705. if (!this.chromaticAberration.isReady()) {
  76706. this.chromaticAberration.updateEffect();
  76707. }
  76708. this.addEffect(this._chromaticAberrationEffect);
  76709. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76710. }
  76711. if (this.fxaaEnabled) {
  76712. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76713. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76714. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76715. }
  76716. if (this._cameras !== null) {
  76717. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76718. }
  76719. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76720. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76721. }
  76722. };
  76723. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76724. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76725. for (var i = 0; i < this._cameras.length; i++) {
  76726. var camera = this._cameras[i];
  76727. if (this.imageProcessing) {
  76728. this.imageProcessing.dispose(camera);
  76729. }
  76730. if (this.fxaa) {
  76731. this.fxaa.dispose(camera);
  76732. }
  76733. // These are created in the constructor and should not be disposed on every pipeline change
  76734. if (disposeNonRecreated) {
  76735. if (this.sharpen) {
  76736. this.sharpen.dispose(camera);
  76737. }
  76738. if (this.depthOfField) {
  76739. this.depthOfField.disposeEffects(camera);
  76740. }
  76741. if (this.bloom) {
  76742. this.bloom.disposeEffects(camera);
  76743. }
  76744. if (this.chromaticAberration) {
  76745. this.chromaticAberration.dispose(camera);
  76746. }
  76747. if (this.grain) {
  76748. this.grain.dispose(camera);
  76749. }
  76750. if (this._glowLayer) {
  76751. this._glowLayer.dispose();
  76752. }
  76753. }
  76754. }
  76755. this.imageProcessing = null;
  76756. this.fxaa = null;
  76757. if (disposeNonRecreated) {
  76758. this.sharpen = null;
  76759. this._sharpenEffect = null;
  76760. this.depthOfField = null;
  76761. this.bloom = null;
  76762. this.chromaticAberration = null;
  76763. this._chromaticAberrationEffect = null;
  76764. this.grain = null;
  76765. this._grainEffect = null;
  76766. this._glowLayer = null;
  76767. }
  76768. };
  76769. /**
  76770. * Adds a camera to the pipeline
  76771. * @param camera the camera to be added
  76772. */
  76773. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76774. this._camerasToBeAttached.push(camera);
  76775. this._buildPipeline();
  76776. };
  76777. /**
  76778. * Removes a camera from the pipeline
  76779. * @param camera the camera to remove
  76780. */
  76781. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76782. var index = this._camerasToBeAttached.indexOf(camera);
  76783. this._camerasToBeAttached.splice(index, 1);
  76784. this._buildPipeline();
  76785. };
  76786. /**
  76787. * Dispose of the pipeline and stop all post processes
  76788. */
  76789. DefaultRenderingPipeline.prototype.dispose = function () {
  76790. this._disposePostProcesses(true);
  76791. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76792. this._scene.autoClear = true;
  76793. if (this._resizeObserver) {
  76794. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76795. this._resizeObserver = null;
  76796. }
  76797. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76798. _super.prototype.dispose.call(this);
  76799. };
  76800. /**
  76801. * Serialize the rendering pipeline (Used when exporting)
  76802. * @returns the serialized object
  76803. */
  76804. DefaultRenderingPipeline.prototype.serialize = function () {
  76805. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76806. serializationObject.customType = "DefaultRenderingPipeline";
  76807. return serializationObject;
  76808. };
  76809. /**
  76810. * Parse the serialized pipeline
  76811. * @param source Source pipeline.
  76812. * @param scene The scene to load the pipeline to.
  76813. * @param rootUrl The URL of the serialized pipeline.
  76814. * @returns An instantiated pipeline from the serialized object.
  76815. */
  76816. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76817. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76818. };
  76819. __decorate([
  76820. BABYLON.serialize()
  76821. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76822. __decorate([
  76823. BABYLON.serialize()
  76824. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76825. __decorate([
  76826. BABYLON.serialize()
  76827. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76828. __decorate([
  76829. BABYLON.serialize()
  76830. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76831. __decorate([
  76832. BABYLON.serialize()
  76833. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76834. __decorate([
  76835. BABYLON.serialize()
  76836. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76840. __decorate([
  76841. BABYLON.serialize()
  76842. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76843. __decorate([
  76844. BABYLON.serialize()
  76845. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76846. __decorate([
  76847. BABYLON.serialize()
  76848. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76849. __decorate([
  76850. BABYLON.serialize()
  76851. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76852. __decorate([
  76853. BABYLON.serialize()
  76854. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76855. __decorate([
  76856. BABYLON.serialize()
  76857. ], DefaultRenderingPipeline.prototype, "samples", null);
  76858. __decorate([
  76859. BABYLON.serialize()
  76860. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76861. __decorate([
  76862. BABYLON.serialize()
  76863. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76864. __decorate([
  76865. BABYLON.serialize()
  76866. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76867. __decorate([
  76868. BABYLON.serialize()
  76869. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76870. return DefaultRenderingPipeline;
  76871. }(BABYLON.PostProcessRenderPipeline));
  76872. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76873. })(BABYLON || (BABYLON = {}));
  76874. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76875. var BABYLON;
  76876. (function (BABYLON) {
  76877. /**
  76878. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76879. */
  76880. var GeometryBufferRenderer = /** @class */ (function () {
  76881. /**
  76882. * Creates a new G Buffer for the scene
  76883. * @param scene The scene the buffer belongs to
  76884. * @param ratio How big is the buffer related to the main canvas.
  76885. */
  76886. function GeometryBufferRenderer(scene, ratio) {
  76887. if (ratio === void 0) { ratio = 1; }
  76888. this._enablePosition = false;
  76889. this._scene = scene;
  76890. this._ratio = ratio;
  76891. // Render target
  76892. this._createRenderTargets();
  76893. }
  76894. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76895. /**
  76896. * Set the render list (meshes to be rendered) used in the G buffer.
  76897. */
  76898. set: function (meshes) {
  76899. this._multiRenderTarget.renderList = meshes;
  76900. },
  76901. enumerable: true,
  76902. configurable: true
  76903. });
  76904. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76905. /**
  76906. * Gets wether or not G buffer are supported by the running hardware.
  76907. * This requires draw buffer supports
  76908. */
  76909. get: function () {
  76910. return this._multiRenderTarget.isSupported;
  76911. },
  76912. enumerable: true,
  76913. configurable: true
  76914. });
  76915. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76916. /**
  76917. * Gets wether or not position are enabled for the G buffer.
  76918. */
  76919. get: function () {
  76920. return this._enablePosition;
  76921. },
  76922. /**
  76923. * Sets wether or not position are enabled for the G buffer.
  76924. */
  76925. set: function (enable) {
  76926. this._enablePosition = enable;
  76927. this.dispose();
  76928. this._createRenderTargets();
  76929. },
  76930. enumerable: true,
  76931. configurable: true
  76932. });
  76933. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76934. /**
  76935. * Gets the scene associated with the buffer.
  76936. */
  76937. get: function () {
  76938. return this._scene;
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76944. /**
  76945. * Gets the ratio used by the buffer during its creation.
  76946. * How big is the buffer related to the main canvas.
  76947. */
  76948. get: function () {
  76949. return this._ratio;
  76950. },
  76951. enumerable: true,
  76952. configurable: true
  76953. });
  76954. /**
  76955. * Checks wether everything is ready to render a submesh to the G buffer.
  76956. * @param subMesh the submesh to check readiness for
  76957. * @param useInstances is the mesh drawn using instance or not
  76958. * @returns true if ready otherwise false
  76959. */
  76960. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76961. var material = subMesh.getMaterial();
  76962. if (material && material.disableDepthWrite) {
  76963. return false;
  76964. }
  76965. var defines = [];
  76966. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76967. var mesh = subMesh.getMesh();
  76968. // Alpha test
  76969. if (material && material.needAlphaTesting()) {
  76970. defines.push("#define ALPHATEST");
  76971. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76972. attribs.push(BABYLON.VertexBuffer.UVKind);
  76973. defines.push("#define UV1");
  76974. }
  76975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76976. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76977. defines.push("#define UV2");
  76978. }
  76979. }
  76980. // Buffers
  76981. if (this._enablePosition) {
  76982. defines.push("#define POSITION");
  76983. }
  76984. // Bones
  76985. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76988. if (mesh.numBoneInfluencers > 4) {
  76989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76991. }
  76992. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76993. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76994. }
  76995. else {
  76996. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76997. }
  76998. // Instances
  76999. if (useInstances) {
  77000. defines.push("#define INSTANCES");
  77001. attribs.push("world0");
  77002. attribs.push("world1");
  77003. attribs.push("world2");
  77004. attribs.push("world3");
  77005. }
  77006. // Get correct effect
  77007. var join = defines.join("\n");
  77008. if (this._cachedDefines !== join) {
  77009. this._cachedDefines = join;
  77010. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77011. }
  77012. return this._effect.isReady();
  77013. };
  77014. /**
  77015. * Gets the current underlying G Buffer.
  77016. * @returns the buffer
  77017. */
  77018. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77019. return this._multiRenderTarget;
  77020. };
  77021. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77022. /**
  77023. * Gets the number of samples used to render the buffer (anti aliasing).
  77024. */
  77025. get: function () {
  77026. return this._multiRenderTarget.samples;
  77027. },
  77028. /**
  77029. * Sets the number of samples used to render the buffer (anti aliasing).
  77030. */
  77031. set: function (value) {
  77032. this._multiRenderTarget.samples = value;
  77033. },
  77034. enumerable: true,
  77035. configurable: true
  77036. });
  77037. /**
  77038. * Disposes the renderer and frees up associated resources.
  77039. */
  77040. GeometryBufferRenderer.prototype.dispose = function () {
  77041. this.getGBuffer().dispose();
  77042. };
  77043. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77044. var _this = this;
  77045. var engine = this._scene.getEngine();
  77046. var count = this._enablePosition ? 3 : 2;
  77047. 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 });
  77048. if (!this.isSupported) {
  77049. return;
  77050. }
  77051. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77052. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77053. this._multiRenderTarget.refreshRate = 1;
  77054. this._multiRenderTarget.renderParticles = false;
  77055. this._multiRenderTarget.renderList = null;
  77056. // set default depth value to 1.0 (far away)
  77057. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77058. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77059. });
  77060. // Custom render function
  77061. var renderSubMesh = function (subMesh) {
  77062. var mesh = subMesh.getRenderingMesh();
  77063. var scene = _this._scene;
  77064. var engine = scene.getEngine();
  77065. var material = subMesh.getMaterial();
  77066. if (!material) {
  77067. return;
  77068. }
  77069. // Culling
  77070. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77071. // Managing instances
  77072. var batch = mesh._getInstancesRenderList(subMesh._id);
  77073. if (batch.mustReturn) {
  77074. return;
  77075. }
  77076. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77077. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77078. engine.enableEffect(_this._effect);
  77079. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77080. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77081. _this._effect.setMatrix("view", scene.getViewMatrix());
  77082. // Alpha test
  77083. if (material && material.needAlphaTesting()) {
  77084. var alphaTexture = material.getAlphaTestTexture();
  77085. if (alphaTexture) {
  77086. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77087. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77088. }
  77089. }
  77090. // Bones
  77091. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77092. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77093. }
  77094. // Draw
  77095. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77096. }
  77097. };
  77098. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77099. var index;
  77100. if (depthOnlySubMeshes.length) {
  77101. engine.setColorWrite(false);
  77102. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77103. renderSubMesh(depthOnlySubMeshes.data[index]);
  77104. }
  77105. engine.setColorWrite(true);
  77106. }
  77107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77108. renderSubMesh(opaqueSubMeshes.data[index]);
  77109. }
  77110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77111. renderSubMesh(alphaTestSubMeshes.data[index]);
  77112. }
  77113. };
  77114. };
  77115. return GeometryBufferRenderer;
  77116. }());
  77117. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77118. })(BABYLON || (BABYLON = {}));
  77119. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77120. var BABYLON;
  77121. (function (BABYLON) {
  77122. /**
  77123. * This groups together the common properties used for image processing either in direct forward pass
  77124. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77125. * or not.
  77126. */
  77127. var ImageProcessingConfiguration = /** @class */ (function () {
  77128. function ImageProcessingConfiguration() {
  77129. /**
  77130. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77131. */
  77132. this.colorCurves = new BABYLON.ColorCurves();
  77133. this._colorCurvesEnabled = false;
  77134. this._colorGradingEnabled = false;
  77135. this._colorGradingWithGreenDepth = true;
  77136. this._colorGradingBGR = true;
  77137. this._exposure = 1.0;
  77138. this._toneMappingEnabled = false;
  77139. this._contrast = 1.0;
  77140. /**
  77141. * Vignette stretch size.
  77142. */
  77143. this.vignetteStretch = 0;
  77144. /**
  77145. * Vignette centre X Offset.
  77146. */
  77147. this.vignetteCentreX = 0;
  77148. /**
  77149. * Vignette centre Y Offset.
  77150. */
  77151. this.vignetteCentreY = 0;
  77152. /**
  77153. * Vignette weight or intensity of the vignette effect.
  77154. */
  77155. this.vignetteWeight = 1.5;
  77156. /**
  77157. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77158. * if vignetteEnabled is set to true.
  77159. */
  77160. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77161. /**
  77162. * Camera field of view used by the Vignette effect.
  77163. */
  77164. this.vignetteCameraFov = 0.5;
  77165. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77166. this._vignetteEnabled = false;
  77167. this._applyByPostProcess = false;
  77168. this._isEnabled = true;
  77169. /**
  77170. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77171. */
  77172. this.onUpdateParameters = new BABYLON.Observable();
  77173. }
  77174. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77175. /**
  77176. * Gets wether the color curves effect is enabled.
  77177. */
  77178. get: function () {
  77179. return this._colorCurvesEnabled;
  77180. },
  77181. /**
  77182. * Sets wether the color curves effect is enabled.
  77183. */
  77184. set: function (value) {
  77185. if (this._colorCurvesEnabled === value) {
  77186. return;
  77187. }
  77188. this._colorCurvesEnabled = value;
  77189. this._updateParameters();
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77195. /**
  77196. * Gets wether the color grading effect is enabled.
  77197. */
  77198. get: function () {
  77199. return this._colorGradingEnabled;
  77200. },
  77201. /**
  77202. * Sets wether the color grading effect is enabled.
  77203. */
  77204. set: function (value) {
  77205. if (this._colorGradingEnabled === value) {
  77206. return;
  77207. }
  77208. this._colorGradingEnabled = value;
  77209. this._updateParameters();
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77215. /**
  77216. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77217. */
  77218. get: function () {
  77219. return this._colorGradingWithGreenDepth;
  77220. },
  77221. /**
  77222. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77223. */
  77224. set: function (value) {
  77225. if (this._colorGradingWithGreenDepth === value) {
  77226. return;
  77227. }
  77228. this._colorGradingWithGreenDepth = value;
  77229. this._updateParameters();
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77235. /**
  77236. * Gets wether the color grading texture contains BGR values.
  77237. */
  77238. get: function () {
  77239. return this._colorGradingBGR;
  77240. },
  77241. /**
  77242. * Sets wether the color grading texture contains BGR values.
  77243. */
  77244. set: function (value) {
  77245. if (this._colorGradingBGR === value) {
  77246. return;
  77247. }
  77248. this._colorGradingBGR = value;
  77249. this._updateParameters();
  77250. },
  77251. enumerable: true,
  77252. configurable: true
  77253. });
  77254. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77255. /**
  77256. * Gets the Exposure used in the effect.
  77257. */
  77258. get: function () {
  77259. return this._exposure;
  77260. },
  77261. /**
  77262. * Sets the Exposure used in the effect.
  77263. */
  77264. set: function (value) {
  77265. if (this._exposure === value) {
  77266. return;
  77267. }
  77268. this._exposure = value;
  77269. this._updateParameters();
  77270. },
  77271. enumerable: true,
  77272. configurable: true
  77273. });
  77274. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77275. /**
  77276. * Gets wether the tone mapping effect is enabled.
  77277. */
  77278. get: function () {
  77279. return this._toneMappingEnabled;
  77280. },
  77281. /**
  77282. * Sets wether the tone mapping effect is enabled.
  77283. */
  77284. set: function (value) {
  77285. if (this._toneMappingEnabled === value) {
  77286. return;
  77287. }
  77288. this._toneMappingEnabled = value;
  77289. this._updateParameters();
  77290. },
  77291. enumerable: true,
  77292. configurable: true
  77293. });
  77294. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77295. /**
  77296. * Gets the contrast used in the effect.
  77297. */
  77298. get: function () {
  77299. return this._contrast;
  77300. },
  77301. /**
  77302. * Sets the contrast used in the effect.
  77303. */
  77304. set: function (value) {
  77305. if (this._contrast === value) {
  77306. return;
  77307. }
  77308. this._contrast = value;
  77309. this._updateParameters();
  77310. },
  77311. enumerable: true,
  77312. configurable: true
  77313. });
  77314. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77315. /**
  77316. * Gets the vignette blend mode allowing different kind of effect.
  77317. */
  77318. get: function () {
  77319. return this._vignetteBlendMode;
  77320. },
  77321. /**
  77322. * Sets the vignette blend mode allowing different kind of effect.
  77323. */
  77324. set: function (value) {
  77325. if (this._vignetteBlendMode === value) {
  77326. return;
  77327. }
  77328. this._vignetteBlendMode = value;
  77329. this._updateParameters();
  77330. },
  77331. enumerable: true,
  77332. configurable: true
  77333. });
  77334. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77335. /**
  77336. * Gets wether the vignette effect is enabled.
  77337. */
  77338. get: function () {
  77339. return this._vignetteEnabled;
  77340. },
  77341. /**
  77342. * Sets wether the vignette effect is enabled.
  77343. */
  77344. set: function (value) {
  77345. if (this._vignetteEnabled === value) {
  77346. return;
  77347. }
  77348. this._vignetteEnabled = value;
  77349. this._updateParameters();
  77350. },
  77351. enumerable: true,
  77352. configurable: true
  77353. });
  77354. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77355. /**
  77356. * Gets wether the image processing is applied through a post process or not.
  77357. */
  77358. get: function () {
  77359. return this._applyByPostProcess;
  77360. },
  77361. /**
  77362. * Sets wether the image processing is applied through a post process or not.
  77363. */
  77364. set: function (value) {
  77365. if (this._applyByPostProcess === value) {
  77366. return;
  77367. }
  77368. this._applyByPostProcess = value;
  77369. this._updateParameters();
  77370. },
  77371. enumerable: true,
  77372. configurable: true
  77373. });
  77374. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77375. /**
  77376. * Gets wether the image processing is enabled or not.
  77377. */
  77378. get: function () {
  77379. return this._isEnabled;
  77380. },
  77381. /**
  77382. * Sets wether the image processing is enabled or not.
  77383. */
  77384. set: function (value) {
  77385. if (this._isEnabled === value) {
  77386. return;
  77387. }
  77388. this._isEnabled = value;
  77389. this._updateParameters();
  77390. },
  77391. enumerable: true,
  77392. configurable: true
  77393. });
  77394. /**
  77395. * Method called each time the image processing information changes requires to recompile the effect.
  77396. */
  77397. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77398. this.onUpdateParameters.notifyObservers(this);
  77399. };
  77400. ImageProcessingConfiguration.prototype.getClassName = function () {
  77401. return "ImageProcessingConfiguration";
  77402. };
  77403. /**
  77404. * Prepare the list of uniforms associated with the Image Processing effects.
  77405. * @param uniformsList The list of uniforms used in the effect
  77406. * @param defines the list of defines currently in use
  77407. */
  77408. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77409. if (defines.EXPOSURE) {
  77410. uniforms.push("exposureLinear");
  77411. }
  77412. if (defines.CONTRAST) {
  77413. uniforms.push("contrast");
  77414. }
  77415. if (defines.COLORGRADING) {
  77416. uniforms.push("colorTransformSettings");
  77417. }
  77418. if (defines.VIGNETTE) {
  77419. uniforms.push("vInverseScreenSize");
  77420. uniforms.push("vignetteSettings1");
  77421. uniforms.push("vignetteSettings2");
  77422. }
  77423. if (defines.COLORCURVES) {
  77424. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77425. }
  77426. };
  77427. /**
  77428. * Prepare the list of samplers associated with the Image Processing effects.
  77429. * @param uniformsList The list of uniforms used in the effect
  77430. * @param defines the list of defines currently in use
  77431. */
  77432. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77433. if (defines.COLORGRADING) {
  77434. samplersList.push("txColorTransform");
  77435. }
  77436. };
  77437. /**
  77438. * Prepare the list of defines associated to the shader.
  77439. * @param defines the list of defines to complete
  77440. */
  77441. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77442. if (forPostProcess === void 0) { forPostProcess = false; }
  77443. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77444. defines.VIGNETTE = false;
  77445. defines.TONEMAPPING = false;
  77446. defines.CONTRAST = false;
  77447. defines.EXPOSURE = false;
  77448. defines.COLORCURVES = false;
  77449. defines.COLORGRADING = false;
  77450. defines.COLORGRADING3D = false;
  77451. defines.IMAGEPROCESSING = false;
  77452. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77453. return;
  77454. }
  77455. defines.VIGNETTE = this.vignetteEnabled;
  77456. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77457. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77458. defines.TONEMAPPING = this.toneMappingEnabled;
  77459. defines.CONTRAST = (this.contrast !== 1.0);
  77460. defines.EXPOSURE = (this.exposure !== 1.0);
  77461. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77462. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77463. if (defines.COLORGRADING) {
  77464. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77465. }
  77466. else {
  77467. defines.COLORGRADING3D = false;
  77468. }
  77469. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77470. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77471. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77472. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77473. };
  77474. /**
  77475. * Returns true if all the image processing information are ready.
  77476. */
  77477. ImageProcessingConfiguration.prototype.isReady = function () {
  77478. // Color Grading texure can not be none blocking.
  77479. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77480. };
  77481. /**
  77482. * Binds the image processing to the shader.
  77483. * @param effect The effect to bind to
  77484. */
  77485. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77486. if (aspectRatio === void 0) { aspectRatio = 1; }
  77487. // Color Curves
  77488. if (this._colorCurvesEnabled && this.colorCurves) {
  77489. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77490. }
  77491. // Vignette
  77492. if (this._vignetteEnabled) {
  77493. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77494. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77495. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77496. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77497. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77498. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77499. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77500. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77501. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77502. var vignettePower = -2.0 * this.vignetteWeight;
  77503. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77504. }
  77505. // Exposure
  77506. effect.setFloat("exposureLinear", this.exposure);
  77507. // Contrast
  77508. effect.setFloat("contrast", this.contrast);
  77509. // Color transform settings
  77510. if (this.colorGradingTexture) {
  77511. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77512. var textureSize = this.colorGradingTexture.getSize().height;
  77513. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77514. 0.5 / textureSize, // textureOffset
  77515. textureSize, // textureSize
  77516. this.colorGradingTexture.level // weight
  77517. );
  77518. }
  77519. };
  77520. /**
  77521. * Clones the current image processing instance.
  77522. * @return The cloned image processing
  77523. */
  77524. ImageProcessingConfiguration.prototype.clone = function () {
  77525. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77526. };
  77527. /**
  77528. * Serializes the current image processing instance to a json representation.
  77529. * @return a JSON representation
  77530. */
  77531. ImageProcessingConfiguration.prototype.serialize = function () {
  77532. return BABYLON.SerializationHelper.Serialize(this);
  77533. };
  77534. /**
  77535. * Parses the image processing from a json representation.
  77536. * @param source the JSON source to parse
  77537. * @return The parsed image processing
  77538. */
  77539. ImageProcessingConfiguration.Parse = function (source) {
  77540. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77541. };
  77542. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77543. /**
  77544. * Used to apply the vignette as a mix with the pixel color.
  77545. */
  77546. get: function () {
  77547. return this._VIGNETTEMODE_MULTIPLY;
  77548. },
  77549. enumerable: true,
  77550. configurable: true
  77551. });
  77552. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77553. /**
  77554. * Used to apply the vignette as a replacement of the pixel color.
  77555. */
  77556. get: function () {
  77557. return this._VIGNETTEMODE_OPAQUE;
  77558. },
  77559. enumerable: true,
  77560. configurable: true
  77561. });
  77562. // Static constants associated to the image processing.
  77563. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77564. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77565. __decorate([
  77566. BABYLON.serializeAsColorCurves()
  77567. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77568. __decorate([
  77569. BABYLON.serialize()
  77570. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77571. __decorate([
  77572. BABYLON.serializeAsTexture()
  77573. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77574. __decorate([
  77575. BABYLON.serialize()
  77576. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77577. __decorate([
  77578. BABYLON.serialize()
  77579. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77580. __decorate([
  77581. BABYLON.serialize()
  77582. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77583. __decorate([
  77584. BABYLON.serialize()
  77585. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77586. __decorate([
  77587. BABYLON.serialize()
  77588. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77589. __decorate([
  77590. BABYLON.serialize()
  77591. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77592. __decorate([
  77593. BABYLON.serialize()
  77594. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77595. __decorate([
  77596. BABYLON.serialize()
  77597. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77598. __decorate([
  77599. BABYLON.serialize()
  77600. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77601. __decorate([
  77602. BABYLON.serialize()
  77603. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77604. __decorate([
  77605. BABYLON.serializeAsColor4()
  77606. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77607. __decorate([
  77608. BABYLON.serialize()
  77609. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77610. __decorate([
  77611. BABYLON.serialize()
  77612. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77613. __decorate([
  77614. BABYLON.serialize()
  77615. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77616. __decorate([
  77617. BABYLON.serialize()
  77618. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77619. __decorate([
  77620. BABYLON.serialize()
  77621. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77622. return ImageProcessingConfiguration;
  77623. }());
  77624. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77625. })(BABYLON || (BABYLON = {}));
  77626. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77627. var BABYLON;
  77628. (function (BABYLON) {
  77629. /**
  77630. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77631. * It can help converting any input color in a desired output one. This can then be used to create effects
  77632. * from sepia, black and white to sixties or futuristic rendering...
  77633. *
  77634. * The only supported format is currently 3dl.
  77635. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77636. */
  77637. var ColorGradingTexture = /** @class */ (function (_super) {
  77638. __extends(ColorGradingTexture, _super);
  77639. /**
  77640. * Instantiates a ColorGradingTexture from the following parameters.
  77641. *
  77642. * @param url The location of the color gradind data (currently only supporting 3dl)
  77643. * @param scene The scene the texture will be used in
  77644. */
  77645. function ColorGradingTexture(url, scene) {
  77646. var _this = _super.call(this, scene) || this;
  77647. if (!url) {
  77648. return _this;
  77649. }
  77650. _this._engine = scene.getEngine();
  77651. _this._textureMatrix = BABYLON.Matrix.Identity();
  77652. _this.name = url;
  77653. _this.url = url;
  77654. _this.hasAlpha = false;
  77655. _this.isCube = false;
  77656. _this.is3D = _this._engine.webGLVersion > 1;
  77657. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77658. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77659. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77660. _this.anisotropicFilteringLevel = 1;
  77661. _this._texture = _this._getFromCache(url, true);
  77662. if (!_this._texture) {
  77663. if (!scene.useDelayedTextureLoading) {
  77664. _this.loadTexture();
  77665. }
  77666. else {
  77667. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77668. }
  77669. }
  77670. return _this;
  77671. }
  77672. /**
  77673. * Returns the texture matrix used in most of the material.
  77674. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77675. */
  77676. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77677. return this._textureMatrix;
  77678. };
  77679. /**
  77680. * Occurs when the file being loaded is a .3dl LUT file.
  77681. */
  77682. ColorGradingTexture.prototype.load3dlTexture = function () {
  77683. var engine = this._engine;
  77684. var texture;
  77685. if (engine.webGLVersion === 1) {
  77686. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77687. }
  77688. else {
  77689. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77690. }
  77691. this._texture = texture;
  77692. var callback = function (text) {
  77693. if (typeof text !== "string") {
  77694. return;
  77695. }
  77696. var data = null;
  77697. var tempData = null;
  77698. var line;
  77699. var lines = text.split('\n');
  77700. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77701. var maxColor = 0;
  77702. for (var i = 0; i < lines.length; i++) {
  77703. line = lines[i];
  77704. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77705. continue;
  77706. if (line.indexOf('#') === 0)
  77707. continue;
  77708. var words = line.split(" ");
  77709. if (size === 0) {
  77710. // Number of space + one
  77711. size = words.length;
  77712. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77713. tempData = new Float32Array(size * size * size * 4);
  77714. continue;
  77715. }
  77716. if (size != 0) {
  77717. var r = Math.max(parseInt(words[0]), 0);
  77718. var g = Math.max(parseInt(words[1]), 0);
  77719. var b = Math.max(parseInt(words[2]), 0);
  77720. maxColor = Math.max(r, maxColor);
  77721. maxColor = Math.max(g, maxColor);
  77722. maxColor = Math.max(b, maxColor);
  77723. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77724. if (tempData) {
  77725. tempData[pixelStorageIndex + 0] = r;
  77726. tempData[pixelStorageIndex + 1] = g;
  77727. tempData[pixelStorageIndex + 2] = b;
  77728. }
  77729. pixelIndexSlice++;
  77730. if (pixelIndexSlice % size == 0) {
  77731. pixelIndexH++;
  77732. pixelIndexSlice = 0;
  77733. if (pixelIndexH % size == 0) {
  77734. pixelIndexW++;
  77735. pixelIndexH = 0;
  77736. }
  77737. }
  77738. }
  77739. }
  77740. if (tempData && data) {
  77741. for (var i = 0; i < tempData.length; i++) {
  77742. if (i > 0 && (i + 1) % 4 === 0) {
  77743. data[i] = 255;
  77744. }
  77745. else {
  77746. var value = tempData[i];
  77747. data[i] = (value / maxColor * 255);
  77748. }
  77749. }
  77750. }
  77751. if (texture.is3D) {
  77752. texture.updateSize(size, size, size);
  77753. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77754. }
  77755. else {
  77756. texture.updateSize(size * size, size);
  77757. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77758. }
  77759. };
  77760. var scene = this.getScene();
  77761. if (scene) {
  77762. scene._loadFile(this.url, callback);
  77763. }
  77764. else {
  77765. this._engine._loadFile(this.url, callback);
  77766. }
  77767. return this._texture;
  77768. };
  77769. /**
  77770. * Starts the loading process of the texture.
  77771. */
  77772. ColorGradingTexture.prototype.loadTexture = function () {
  77773. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77774. this.load3dlTexture();
  77775. }
  77776. };
  77777. /**
  77778. * Clones the color gradind texture.
  77779. */
  77780. ColorGradingTexture.prototype.clone = function () {
  77781. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77782. // Base texture
  77783. newTexture.level = this.level;
  77784. return newTexture;
  77785. };
  77786. /**
  77787. * Called during delayed load for textures.
  77788. */
  77789. ColorGradingTexture.prototype.delayLoad = function () {
  77790. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77791. return;
  77792. }
  77793. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77794. this._texture = this._getFromCache(this.url, true);
  77795. if (!this._texture) {
  77796. this.loadTexture();
  77797. }
  77798. };
  77799. /**
  77800. * Parses a color grading texture serialized by Babylon.
  77801. * @param parsedTexture The texture information being parsedTexture
  77802. * @param scene The scene to load the texture in
  77803. * @param rootUrl The root url of the data assets to load
  77804. * @return A color gradind texture
  77805. */
  77806. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77807. var texture = null;
  77808. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77809. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77810. texture.name = parsedTexture.name;
  77811. texture.level = parsedTexture.level;
  77812. }
  77813. return texture;
  77814. };
  77815. /**
  77816. * Serializes the LUT texture to json format.
  77817. */
  77818. ColorGradingTexture.prototype.serialize = function () {
  77819. if (!this.name) {
  77820. return null;
  77821. }
  77822. var serializationObject = {};
  77823. serializationObject.name = this.name;
  77824. serializationObject.level = this.level;
  77825. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77826. return serializationObject;
  77827. };
  77828. /**
  77829. * Empty line regex stored for GC.
  77830. */
  77831. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77832. return ColorGradingTexture;
  77833. }(BABYLON.BaseTexture));
  77834. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77835. })(BABYLON || (BABYLON = {}));
  77836. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77837. var BABYLON;
  77838. (function (BABYLON) {
  77839. /**
  77840. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77841. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77842. * 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;
  77843. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77844. */
  77845. var ColorCurves = /** @class */ (function () {
  77846. function ColorCurves() {
  77847. this._dirty = true;
  77848. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77849. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77850. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77851. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77852. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77853. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77854. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77855. this._globalHue = 30;
  77856. this._globalDensity = 0;
  77857. this._globalSaturation = 0;
  77858. this._globalExposure = 0;
  77859. this._highlightsHue = 30;
  77860. this._highlightsDensity = 0;
  77861. this._highlightsSaturation = 0;
  77862. this._highlightsExposure = 0;
  77863. this._midtonesHue = 30;
  77864. this._midtonesDensity = 0;
  77865. this._midtonesSaturation = 0;
  77866. this._midtonesExposure = 0;
  77867. this._shadowsHue = 30;
  77868. this._shadowsDensity = 0;
  77869. this._shadowsSaturation = 0;
  77870. this._shadowsExposure = 0;
  77871. }
  77872. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77873. /**
  77874. * Gets the global Hue value.
  77875. * 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).
  77876. */
  77877. get: function () {
  77878. return this._globalHue;
  77879. },
  77880. /**
  77881. * Sets the global Hue value.
  77882. * 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).
  77883. */
  77884. set: function (value) {
  77885. this._globalHue = value;
  77886. this._dirty = true;
  77887. },
  77888. enumerable: true,
  77889. configurable: true
  77890. });
  77891. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77892. /**
  77893. * Gets the global Density value.
  77894. * 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.
  77895. * Values less than zero provide a filter of opposite hue.
  77896. */
  77897. get: function () {
  77898. return this._globalDensity;
  77899. },
  77900. /**
  77901. * Sets the global Density value.
  77902. * 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.
  77903. * Values less than zero provide a filter of opposite hue.
  77904. */
  77905. set: function (value) {
  77906. this._globalDensity = value;
  77907. this._dirty = true;
  77908. },
  77909. enumerable: true,
  77910. configurable: true
  77911. });
  77912. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77913. /**
  77914. * Gets the global Saturation value.
  77915. * 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.
  77916. */
  77917. get: function () {
  77918. return this._globalSaturation;
  77919. },
  77920. /**
  77921. * Sets the global Saturation value.
  77922. * 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.
  77923. */
  77924. set: function (value) {
  77925. this._globalSaturation = value;
  77926. this._dirty = true;
  77927. },
  77928. enumerable: true,
  77929. configurable: true
  77930. });
  77931. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77932. /**
  77933. * Gets the global Exposure value.
  77934. * 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.
  77935. */
  77936. get: function () {
  77937. return this._globalExposure;
  77938. },
  77939. /**
  77940. * Sets the global Exposure value.
  77941. * 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.
  77942. */
  77943. set: function (value) {
  77944. this._globalExposure = value;
  77945. this._dirty = true;
  77946. },
  77947. enumerable: true,
  77948. configurable: true
  77949. });
  77950. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77951. /**
  77952. * Gets the highlights Hue value.
  77953. * 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).
  77954. */
  77955. get: function () {
  77956. return this._highlightsHue;
  77957. },
  77958. /**
  77959. * Sets the highlights Hue value.
  77960. * 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).
  77961. */
  77962. set: function (value) {
  77963. this._highlightsHue = value;
  77964. this._dirty = true;
  77965. },
  77966. enumerable: true,
  77967. configurable: true
  77968. });
  77969. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77970. /**
  77971. * Gets the highlights Density value.
  77972. * 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.
  77973. * Values less than zero provide a filter of opposite hue.
  77974. */
  77975. get: function () {
  77976. return this._highlightsDensity;
  77977. },
  77978. /**
  77979. * Sets the highlights Density value.
  77980. * 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.
  77981. * Values less than zero provide a filter of opposite hue.
  77982. */
  77983. set: function (value) {
  77984. this._highlightsDensity = value;
  77985. this._dirty = true;
  77986. },
  77987. enumerable: true,
  77988. configurable: true
  77989. });
  77990. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77991. /**
  77992. * Gets the highlights Saturation value.
  77993. * 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.
  77994. */
  77995. get: function () {
  77996. return this._highlightsSaturation;
  77997. },
  77998. /**
  77999. * Sets the highlights Saturation value.
  78000. * 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.
  78001. */
  78002. set: function (value) {
  78003. this._highlightsSaturation = value;
  78004. this._dirty = true;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78010. /**
  78011. * Gets the highlights Exposure value.
  78012. * 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.
  78013. */
  78014. get: function () {
  78015. return this._highlightsExposure;
  78016. },
  78017. /**
  78018. * Sets the highlights Exposure value.
  78019. * 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.
  78020. */
  78021. set: function (value) {
  78022. this._highlightsExposure = value;
  78023. this._dirty = true;
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78029. /**
  78030. * Gets the midtones Hue value.
  78031. * 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).
  78032. */
  78033. get: function () {
  78034. return this._midtonesHue;
  78035. },
  78036. /**
  78037. * Sets the midtones Hue value.
  78038. * 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).
  78039. */
  78040. set: function (value) {
  78041. this._midtonesHue = value;
  78042. this._dirty = true;
  78043. },
  78044. enumerable: true,
  78045. configurable: true
  78046. });
  78047. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78048. /**
  78049. * Gets the midtones Density value.
  78050. * 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.
  78051. * Values less than zero provide a filter of opposite hue.
  78052. */
  78053. get: function () {
  78054. return this._midtonesDensity;
  78055. },
  78056. /**
  78057. * Sets the midtones Density value.
  78058. * 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.
  78059. * Values less than zero provide a filter of opposite hue.
  78060. */
  78061. set: function (value) {
  78062. this._midtonesDensity = value;
  78063. this._dirty = true;
  78064. },
  78065. enumerable: true,
  78066. configurable: true
  78067. });
  78068. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78069. /**
  78070. * Gets the midtones Saturation value.
  78071. * 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.
  78072. */
  78073. get: function () {
  78074. return this._midtonesSaturation;
  78075. },
  78076. /**
  78077. * Sets the midtones Saturation value.
  78078. * 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.
  78079. */
  78080. set: function (value) {
  78081. this._midtonesSaturation = value;
  78082. this._dirty = true;
  78083. },
  78084. enumerable: true,
  78085. configurable: true
  78086. });
  78087. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78088. /**
  78089. * Gets the midtones Exposure value.
  78090. * 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.
  78091. */
  78092. get: function () {
  78093. return this._midtonesExposure;
  78094. },
  78095. /**
  78096. * Sets the midtones Exposure value.
  78097. * 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.
  78098. */
  78099. set: function (value) {
  78100. this._midtonesExposure = value;
  78101. this._dirty = true;
  78102. },
  78103. enumerable: true,
  78104. configurable: true
  78105. });
  78106. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78107. /**
  78108. * Gets the shadows Hue value.
  78109. * 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).
  78110. */
  78111. get: function () {
  78112. return this._shadowsHue;
  78113. },
  78114. /**
  78115. * Sets the shadows Hue value.
  78116. * 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).
  78117. */
  78118. set: function (value) {
  78119. this._shadowsHue = value;
  78120. this._dirty = true;
  78121. },
  78122. enumerable: true,
  78123. configurable: true
  78124. });
  78125. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78126. /**
  78127. * Gets the shadows Density value.
  78128. * 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.
  78129. * Values less than zero provide a filter of opposite hue.
  78130. */
  78131. get: function () {
  78132. return this._shadowsDensity;
  78133. },
  78134. /**
  78135. * Sets the shadows Density value.
  78136. * 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.
  78137. * Values less than zero provide a filter of opposite hue.
  78138. */
  78139. set: function (value) {
  78140. this._shadowsDensity = value;
  78141. this._dirty = true;
  78142. },
  78143. enumerable: true,
  78144. configurable: true
  78145. });
  78146. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78147. /**
  78148. * Gets the shadows Saturation value.
  78149. * 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.
  78150. */
  78151. get: function () {
  78152. return this._shadowsSaturation;
  78153. },
  78154. /**
  78155. * Sets the shadows Saturation value.
  78156. * 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.
  78157. */
  78158. set: function (value) {
  78159. this._shadowsSaturation = value;
  78160. this._dirty = true;
  78161. },
  78162. enumerable: true,
  78163. configurable: true
  78164. });
  78165. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78166. /**
  78167. * Gets the shadows Exposure value.
  78168. * 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.
  78169. */
  78170. get: function () {
  78171. return this._shadowsExposure;
  78172. },
  78173. /**
  78174. * Sets the shadows Exposure value.
  78175. * 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.
  78176. */
  78177. set: function (value) {
  78178. this._shadowsExposure = value;
  78179. this._dirty = true;
  78180. },
  78181. enumerable: true,
  78182. configurable: true
  78183. });
  78184. ColorCurves.prototype.getClassName = function () {
  78185. return "ColorCurves";
  78186. };
  78187. /**
  78188. * Binds the color curves to the shader.
  78189. * @param colorCurves The color curve to bind
  78190. * @param effect The effect to bind to
  78191. */
  78192. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78193. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78194. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78195. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78196. if (colorCurves._dirty) {
  78197. colorCurves._dirty = false;
  78198. // Fill in global info.
  78199. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78200. // Compute highlights info.
  78201. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78202. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78203. // Compute midtones info.
  78204. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78205. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78206. // Compute shadows info.
  78207. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78208. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78209. // Compute deltas (neutral is midtones).
  78210. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78211. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78212. }
  78213. if (effect) {
  78214. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78215. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78216. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78217. }
  78218. };
  78219. /**
  78220. * Prepare the list of uniforms associated with the ColorCurves effects.
  78221. * @param uniformsList The list of uniforms used in the effect
  78222. */
  78223. ColorCurves.PrepareUniforms = function (uniformsList) {
  78224. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78225. };
  78226. /**
  78227. * Returns color grading data based on a hue, density, saturation and exposure value.
  78228. * @param filterHue The hue of the color filter.
  78229. * @param filterDensity The density of the color filter.
  78230. * @param saturation The saturation.
  78231. * @param exposure The exposure.
  78232. * @param result The result data container.
  78233. */
  78234. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78235. if (hue == null) {
  78236. return;
  78237. }
  78238. hue = ColorCurves.clamp(hue, 0, 360);
  78239. density = ColorCurves.clamp(density, -100, 100);
  78240. saturation = ColorCurves.clamp(saturation, -100, 100);
  78241. exposure = ColorCurves.clamp(exposure, -100, 100);
  78242. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78243. // so that the maximum filter density is only 50% control. This provides fine control
  78244. // for small values and reasonable range.
  78245. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78246. density *= 0.5;
  78247. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78248. if (density < 0) {
  78249. density *= -1;
  78250. hue = (hue + 180) % 360;
  78251. }
  78252. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78253. result.scaleToRef(2, result);
  78254. result.a = 1 + 0.01 * saturation;
  78255. };
  78256. /**
  78257. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78258. * @param value The input slider value in range [-100,100].
  78259. * @returns Adjusted value.
  78260. */
  78261. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78262. value /= 100;
  78263. var x = Math.abs(value);
  78264. x = Math.pow(x, 2);
  78265. if (value < 0) {
  78266. x *= -1;
  78267. }
  78268. x *= 100;
  78269. return x;
  78270. };
  78271. /**
  78272. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78273. * @param hue The hue (H) input.
  78274. * @param saturation The saturation (S) input.
  78275. * @param brightness The brightness (B) input.
  78276. * @result An RGBA color represented as Vector4.
  78277. */
  78278. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78279. var h = ColorCurves.clamp(hue, 0, 360);
  78280. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78281. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78282. if (s === 0) {
  78283. result.r = v;
  78284. result.g = v;
  78285. result.b = v;
  78286. }
  78287. else {
  78288. // sector 0 to 5
  78289. h /= 60;
  78290. var i = Math.floor(h);
  78291. // fractional part of h
  78292. var f = h - i;
  78293. var p = v * (1 - s);
  78294. var q = v * (1 - s * f);
  78295. var t = v * (1 - s * (1 - f));
  78296. switch (i) {
  78297. case 0:
  78298. result.r = v;
  78299. result.g = t;
  78300. result.b = p;
  78301. break;
  78302. case 1:
  78303. result.r = q;
  78304. result.g = v;
  78305. result.b = p;
  78306. break;
  78307. case 2:
  78308. result.r = p;
  78309. result.g = v;
  78310. result.b = t;
  78311. break;
  78312. case 3:
  78313. result.r = p;
  78314. result.g = q;
  78315. result.b = v;
  78316. break;
  78317. case 4:
  78318. result.r = t;
  78319. result.g = p;
  78320. result.b = v;
  78321. break;
  78322. default: // case 5:
  78323. result.r = v;
  78324. result.g = p;
  78325. result.b = q;
  78326. break;
  78327. }
  78328. }
  78329. result.a = 1;
  78330. };
  78331. /**
  78332. * Returns a value clamped between min and max
  78333. * @param value The value to clamp
  78334. * @param min The minimum of value
  78335. * @param max The maximum of value
  78336. * @returns The clamped value.
  78337. */
  78338. ColorCurves.clamp = function (value, min, max) {
  78339. return Math.min(Math.max(value, min), max);
  78340. };
  78341. /**
  78342. * Clones the current color curve instance.
  78343. * @return The cloned curves
  78344. */
  78345. ColorCurves.prototype.clone = function () {
  78346. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78347. };
  78348. /**
  78349. * Serializes the current color curve instance to a json representation.
  78350. * @return a JSON representation
  78351. */
  78352. ColorCurves.prototype.serialize = function () {
  78353. return BABYLON.SerializationHelper.Serialize(this);
  78354. };
  78355. /**
  78356. * Parses the color curve from a json representation.
  78357. * @param source the JSON source to parse
  78358. * @return The parsed curves
  78359. */
  78360. ColorCurves.Parse = function (source) {
  78361. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78362. };
  78363. __decorate([
  78364. BABYLON.serialize()
  78365. ], ColorCurves.prototype, "_globalHue", void 0);
  78366. __decorate([
  78367. BABYLON.serialize()
  78368. ], ColorCurves.prototype, "_globalDensity", void 0);
  78369. __decorate([
  78370. BABYLON.serialize()
  78371. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78372. __decorate([
  78373. BABYLON.serialize()
  78374. ], ColorCurves.prototype, "_globalExposure", void 0);
  78375. __decorate([
  78376. BABYLON.serialize()
  78377. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78378. __decorate([
  78379. BABYLON.serialize()
  78380. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78381. __decorate([
  78382. BABYLON.serialize()
  78383. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78384. __decorate([
  78385. BABYLON.serialize()
  78386. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78387. __decorate([
  78388. BABYLON.serialize()
  78389. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78390. __decorate([
  78391. BABYLON.serialize()
  78392. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78393. __decorate([
  78394. BABYLON.serialize()
  78395. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78396. __decorate([
  78397. BABYLON.serialize()
  78398. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78399. return ColorCurves;
  78400. }());
  78401. BABYLON.ColorCurves = ColorCurves;
  78402. })(BABYLON || (BABYLON = {}));
  78403. //# sourceMappingURL=babylon.colorCurves.js.map
  78404. var BABYLON;
  78405. (function (BABYLON) {
  78406. var RefractionPostProcess = /** @class */ (function (_super) {
  78407. __extends(RefractionPostProcess, _super);
  78408. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78409. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78410. _this.color = color;
  78411. _this.depth = depth;
  78412. _this.colorLevel = colorLevel;
  78413. _this._ownRefractionTexture = true;
  78414. _this.onActivateObservable.add(function (cam) {
  78415. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78416. });
  78417. _this.onApplyObservable.add(function (effect) {
  78418. effect.setColor3("baseColor", _this.color);
  78419. effect.setFloat("depth", _this.depth);
  78420. effect.setFloat("colorLevel", _this.colorLevel);
  78421. effect.setTexture("refractionSampler", _this._refTexture);
  78422. });
  78423. return _this;
  78424. }
  78425. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78426. /**
  78427. * Gets or sets the refraction texture
  78428. * Please note that you are responsible for disposing the texture if you set it manually
  78429. */
  78430. get: function () {
  78431. return this._refTexture;
  78432. },
  78433. set: function (value) {
  78434. if (this._refTexture && this._ownRefractionTexture) {
  78435. this._refTexture.dispose();
  78436. }
  78437. this._refTexture = value;
  78438. this._ownRefractionTexture = false;
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. // Methods
  78444. RefractionPostProcess.prototype.dispose = function (camera) {
  78445. if (this._refTexture && this._ownRefractionTexture) {
  78446. this._refTexture.dispose();
  78447. this._refTexture = null;
  78448. }
  78449. _super.prototype.dispose.call(this, camera);
  78450. };
  78451. return RefractionPostProcess;
  78452. }(BABYLON.PostProcess));
  78453. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78454. })(BABYLON || (BABYLON = {}));
  78455. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78456. var BABYLON;
  78457. (function (BABYLON) {
  78458. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78459. __extends(BlackAndWhitePostProcess, _super);
  78460. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78461. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78462. _this.degree = 1;
  78463. _this.onApplyObservable.add(function (effect) {
  78464. effect.setFloat("degree", _this.degree);
  78465. });
  78466. return _this;
  78467. }
  78468. return BlackAndWhitePostProcess;
  78469. }(BABYLON.PostProcess));
  78470. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78471. })(BABYLON || (BABYLON = {}));
  78472. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78473. var BABYLON;
  78474. (function (BABYLON) {
  78475. /**
  78476. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78477. * input texture to perform effects such as edge detection or sharpening
  78478. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78479. */
  78480. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78481. __extends(ConvolutionPostProcess, _super);
  78482. /**
  78483. * Creates a new instance ConvolutionPostProcess
  78484. * @param name The name of the effect.
  78485. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78486. * @param options The required width/height ratio to downsize to before computing the render pass.
  78487. * @param camera The camera to apply the render pass to.
  78488. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78489. * @param engine The engine which the post process will be applied. (default: current engine)
  78490. * @param reusable If the post process can be reused on the same frame. (default: false)
  78491. * @param textureType Type of textures used when performing the post process. (default: 0)
  78492. */
  78493. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78494. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78495. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78496. _this.kernel = kernel;
  78497. _this.onApply = function (effect) {
  78498. effect.setFloat2("screenSize", _this.width, _this.height);
  78499. effect.setArray("kernel", _this.kernel);
  78500. };
  78501. return _this;
  78502. }
  78503. // Statics
  78504. /**
  78505. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78506. */
  78507. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78508. /**
  78509. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78510. */
  78511. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78512. /**
  78513. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78514. */
  78515. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78516. /**
  78517. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78518. */
  78519. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78520. /**
  78521. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78522. */
  78523. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78524. /**
  78525. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78526. */
  78527. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78528. return ConvolutionPostProcess;
  78529. }(BABYLON.PostProcess));
  78530. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78531. })(BABYLON || (BABYLON = {}));
  78532. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78533. var BABYLON;
  78534. (function (BABYLON) {
  78535. var FilterPostProcess = /** @class */ (function (_super) {
  78536. __extends(FilterPostProcess, _super);
  78537. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78538. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78539. _this.kernelMatrix = kernelMatrix;
  78540. _this.onApply = function (effect) {
  78541. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78542. };
  78543. return _this;
  78544. }
  78545. return FilterPostProcess;
  78546. }(BABYLON.PostProcess));
  78547. BABYLON.FilterPostProcess = FilterPostProcess;
  78548. })(BABYLON || (BABYLON = {}));
  78549. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78550. var BABYLON;
  78551. (function (BABYLON) {
  78552. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78553. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78554. __extends(VolumetricLightScatteringPostProcess, _super);
  78555. /**
  78556. * @constructor
  78557. * @param {string} name - The post-process name
  78558. * @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)
  78559. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78560. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78561. * @param {number} samples - The post-process quality, default 100
  78562. * @param {number} samplingMode - The post-process filtering mode
  78563. * @param {BABYLON.Engine} engine - The babylon engine
  78564. * @param {boolean} reusable - If the post-process is reusable
  78565. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78566. */
  78567. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78568. if (samples === void 0) { samples = 100; }
  78569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78570. 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;
  78571. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78572. /**
  78573. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78574. */
  78575. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78576. /**
  78577. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78578. */
  78579. _this.useCustomMeshPosition = false;
  78580. /**
  78581. * If the post-process should inverse the light scattering direction
  78582. */
  78583. _this.invert = true;
  78584. /**
  78585. * Array containing the excluded meshes not rendered in the internal pass
  78586. */
  78587. _this.excludedMeshes = new Array();
  78588. /**
  78589. * Controls the overall intensity of the post-process
  78590. */
  78591. _this.exposure = 0.3;
  78592. /**
  78593. * Dissipates each sample's contribution in range [0, 1]
  78594. */
  78595. _this.decay = 0.96815;
  78596. /**
  78597. * Controls the overall intensity of each sample
  78598. */
  78599. _this.weight = 0.58767;
  78600. /**
  78601. * Controls the density of each sample
  78602. */
  78603. _this.density = 0.926;
  78604. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78605. engine = scene.getEngine();
  78606. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78607. // Configure mesh
  78608. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78609. // Configure
  78610. _this._createPass(scene, ratio.passRatio || ratio);
  78611. _this.onActivate = function (camera) {
  78612. if (!_this.isSupported) {
  78613. _this.dispose(camera);
  78614. }
  78615. _this.onActivate = null;
  78616. };
  78617. _this.onApplyObservable.add(function (effect) {
  78618. _this._updateMeshScreenCoordinates(scene);
  78619. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78620. effect.setFloat("exposure", _this.exposure);
  78621. effect.setFloat("decay", _this.decay);
  78622. effect.setFloat("weight", _this.weight);
  78623. effect.setFloat("density", _this.density);
  78624. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78625. });
  78626. return _this;
  78627. }
  78628. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78629. get: function () {
  78630. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78631. return false;
  78632. },
  78633. set: function (useDiffuseColor) {
  78634. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78635. },
  78636. enumerable: true,
  78637. configurable: true
  78638. });
  78639. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78640. return "VolumetricLightScatteringPostProcess";
  78641. };
  78642. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78643. var mesh = subMesh.getMesh();
  78644. // Render this.mesh as default
  78645. if (mesh === this.mesh && mesh.material) {
  78646. return mesh.material.isReady(mesh);
  78647. }
  78648. var defines = [];
  78649. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78650. var material = subMesh.getMaterial();
  78651. // Alpha test
  78652. if (material) {
  78653. if (material.needAlphaTesting()) {
  78654. defines.push("#define ALPHATEST");
  78655. }
  78656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78657. attribs.push(BABYLON.VertexBuffer.UVKind);
  78658. defines.push("#define UV1");
  78659. }
  78660. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78661. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78662. defines.push("#define UV2");
  78663. }
  78664. }
  78665. // Bones
  78666. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78669. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78670. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78671. }
  78672. else {
  78673. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78674. }
  78675. // Instances
  78676. if (useInstances) {
  78677. defines.push("#define INSTANCES");
  78678. attribs.push("world0");
  78679. attribs.push("world1");
  78680. attribs.push("world2");
  78681. attribs.push("world3");
  78682. }
  78683. // Get correct effect
  78684. var join = defines.join("\n");
  78685. if (this._cachedDefines !== join) {
  78686. this._cachedDefines = join;
  78687. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78688. }
  78689. return this._volumetricLightScatteringPass.isReady();
  78690. };
  78691. /**
  78692. * Sets the new light position for light scattering effect
  78693. * @param {BABYLON.Vector3} The new custom light position
  78694. */
  78695. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78696. this.customMeshPosition = position;
  78697. };
  78698. /**
  78699. * Returns the light position for light scattering effect
  78700. * @return {BABYLON.Vector3} The custom light position
  78701. */
  78702. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78703. return this.customMeshPosition;
  78704. };
  78705. /**
  78706. * Disposes the internal assets and detaches the post-process from the camera
  78707. */
  78708. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78709. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78710. if (rttIndex !== -1) {
  78711. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78712. }
  78713. this._volumetricLightScatteringRTT.dispose();
  78714. _super.prototype.dispose.call(this, camera);
  78715. };
  78716. /**
  78717. * Returns the render target texture used by the post-process
  78718. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78719. */
  78720. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78721. return this._volumetricLightScatteringRTT;
  78722. };
  78723. // Private methods
  78724. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78725. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78726. return true;
  78727. }
  78728. return false;
  78729. };
  78730. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78731. var _this = this;
  78732. var engine = scene.getEngine();
  78733. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78734. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78735. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78736. this._volumetricLightScatteringRTT.renderList = null;
  78737. this._volumetricLightScatteringRTT.renderParticles = false;
  78738. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78739. var camera = this.getCamera();
  78740. if (camera) {
  78741. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78742. }
  78743. else {
  78744. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78745. }
  78746. // Custom render function for submeshes
  78747. var renderSubMesh = function (subMesh) {
  78748. var mesh = subMesh.getRenderingMesh();
  78749. if (_this._meshExcluded(mesh)) {
  78750. return;
  78751. }
  78752. var material = subMesh.getMaterial();
  78753. if (!material) {
  78754. return;
  78755. }
  78756. var scene = mesh.getScene();
  78757. var engine = scene.getEngine();
  78758. // Culling
  78759. engine.setState(material.backFaceCulling);
  78760. // Managing instances
  78761. var batch = mesh._getInstancesRenderList(subMesh._id);
  78762. if (batch.mustReturn) {
  78763. return;
  78764. }
  78765. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78766. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78767. var effect = _this._volumetricLightScatteringPass;
  78768. if (mesh === _this.mesh) {
  78769. if (subMesh.effect) {
  78770. effect = subMesh.effect;
  78771. }
  78772. else {
  78773. effect = material.getEffect();
  78774. }
  78775. }
  78776. engine.enableEffect(effect);
  78777. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78778. if (mesh === _this.mesh) {
  78779. material.bind(mesh.getWorldMatrix(), mesh);
  78780. }
  78781. else {
  78782. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78783. // Alpha test
  78784. if (material && material.needAlphaTesting()) {
  78785. var alphaTexture = material.getAlphaTestTexture();
  78786. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78787. if (alphaTexture) {
  78788. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78789. }
  78790. }
  78791. // Bones
  78792. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78793. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78794. }
  78795. }
  78796. // Draw
  78797. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78798. }
  78799. };
  78800. // Render target texture callbacks
  78801. var savedSceneClearColor;
  78802. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78803. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78804. savedSceneClearColor = scene.clearColor;
  78805. scene.clearColor = sceneClearColor;
  78806. });
  78807. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78808. scene.clearColor = savedSceneClearColor;
  78809. });
  78810. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78811. var engine = scene.getEngine();
  78812. var index;
  78813. if (depthOnlySubMeshes.length) {
  78814. engine.setColorWrite(false);
  78815. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78816. renderSubMesh(depthOnlySubMeshes.data[index]);
  78817. }
  78818. engine.setColorWrite(true);
  78819. }
  78820. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78821. renderSubMesh(opaqueSubMeshes.data[index]);
  78822. }
  78823. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78824. renderSubMesh(alphaTestSubMeshes.data[index]);
  78825. }
  78826. if (transparentSubMeshes.length) {
  78827. // Sort sub meshes
  78828. for (index = 0; index < transparentSubMeshes.length; index++) {
  78829. var submesh = transparentSubMeshes.data[index];
  78830. var boundingInfo = submesh.getBoundingInfo();
  78831. if (boundingInfo && scene.activeCamera) {
  78832. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78833. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78834. }
  78835. }
  78836. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78837. sortedArray.sort(function (a, b) {
  78838. // Alpha index first
  78839. if (a._alphaIndex > b._alphaIndex) {
  78840. return 1;
  78841. }
  78842. if (a._alphaIndex < b._alphaIndex) {
  78843. return -1;
  78844. }
  78845. // Then distance to camera
  78846. if (a._distanceToCamera < b._distanceToCamera) {
  78847. return 1;
  78848. }
  78849. if (a._distanceToCamera > b._distanceToCamera) {
  78850. return -1;
  78851. }
  78852. return 0;
  78853. });
  78854. // Render sub meshes
  78855. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78856. for (index = 0; index < sortedArray.length; index++) {
  78857. renderSubMesh(sortedArray[index]);
  78858. }
  78859. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78860. }
  78861. };
  78862. };
  78863. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78864. var transform = scene.getTransformMatrix();
  78865. var meshPosition;
  78866. if (this.useCustomMeshPosition) {
  78867. meshPosition = this.customMeshPosition;
  78868. }
  78869. else if (this.attachedNode) {
  78870. meshPosition = this.attachedNode.position;
  78871. }
  78872. else {
  78873. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78874. }
  78875. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78876. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78877. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78878. if (this.invert)
  78879. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78880. };
  78881. // Static methods
  78882. /**
  78883. * Creates a default mesh for the Volumeric Light Scattering post-process
  78884. * @param {string} The mesh name
  78885. * @param {BABYLON.Scene} The scene where to create the mesh
  78886. * @return {BABYLON.Mesh} the default mesh
  78887. */
  78888. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78889. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78890. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78891. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78892. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78893. mesh.material = material;
  78894. return mesh;
  78895. };
  78896. __decorate([
  78897. BABYLON.serializeAsVector3()
  78898. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78899. __decorate([
  78900. BABYLON.serialize()
  78901. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78902. __decorate([
  78903. BABYLON.serialize()
  78904. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78905. __decorate([
  78906. BABYLON.serializeAsMeshReference()
  78907. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78908. __decorate([
  78909. BABYLON.serialize()
  78910. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78911. __decorate([
  78912. BABYLON.serialize()
  78913. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78914. __decorate([
  78915. BABYLON.serialize()
  78916. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78917. __decorate([
  78918. BABYLON.serialize()
  78919. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78920. __decorate([
  78921. BABYLON.serialize()
  78922. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78923. return VolumetricLightScatteringPostProcess;
  78924. }(BABYLON.PostProcess));
  78925. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78926. })(BABYLON || (BABYLON = {}));
  78927. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78928. //
  78929. // This post-process allows the modification of rendered colors by using
  78930. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78931. //
  78932. // The object needs to be provided an url to a texture containing the color
  78933. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78934. // Use an image editing software to tweak the LUT to match your needs.
  78935. //
  78936. // For an example of a color LUT, see here:
  78937. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78938. // For explanations on color grading, see here:
  78939. // http://udn.epicgames.com/Three/ColorGrading.html
  78940. //
  78941. var BABYLON;
  78942. (function (BABYLON) {
  78943. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78944. __extends(ColorCorrectionPostProcess, _super);
  78945. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78946. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78947. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78948. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78949. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78950. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78951. _this.onApply = function (effect) {
  78952. effect.setTexture("colorTable", _this._colorTableTexture);
  78953. };
  78954. return _this;
  78955. }
  78956. return ColorCorrectionPostProcess;
  78957. }(BABYLON.PostProcess));
  78958. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78959. })(BABYLON || (BABYLON = {}));
  78960. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78961. var BABYLON;
  78962. (function (BABYLON) {
  78963. /** Defines operator used for tonemapping */
  78964. var TonemappingOperator;
  78965. (function (TonemappingOperator) {
  78966. /** Hable */
  78967. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78968. /** Reinhard */
  78969. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78970. /** HejiDawson */
  78971. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78972. /** Photographic */
  78973. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78974. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78975. ;
  78976. /**
  78977. * Defines a post process to apply tone mapping
  78978. */
  78979. var TonemapPostProcess = /** @class */ (function (_super) {
  78980. __extends(TonemapPostProcess, _super);
  78981. /**
  78982. * Creates a new TonemapPostProcess
  78983. * @param name defines the name of the postprocess
  78984. * @param _operator defines the operator to use
  78985. * @param exposureAdjustment defines the required exposure adjustement
  78986. * @param camera defines the camera to use (can be null)
  78987. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78988. * @param engine defines the hosting engine (can be ignore if camera is set)
  78989. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78990. */
  78991. function TonemapPostProcess(name, _operator,
  78992. /** Defines the required exposure adjustement */
  78993. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78995. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78996. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78997. _this._operator = _operator;
  78998. _this.exposureAdjustment = exposureAdjustment;
  78999. var defines = "#define ";
  79000. if (_this._operator === TonemappingOperator.Hable)
  79001. defines += "HABLE_TONEMAPPING";
  79002. else if (_this._operator === TonemappingOperator.Reinhard)
  79003. defines += "REINHARD_TONEMAPPING";
  79004. else if (_this._operator === TonemappingOperator.HejiDawson)
  79005. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79006. else if (_this._operator === TonemappingOperator.Photographic)
  79007. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79008. //sadly a second call to create the effect.
  79009. _this.updateEffect(defines);
  79010. _this.onApply = function (effect) {
  79011. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79012. };
  79013. return _this;
  79014. }
  79015. return TonemapPostProcess;
  79016. }(BABYLON.PostProcess));
  79017. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79018. })(BABYLON || (BABYLON = {}));
  79019. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79020. var BABYLON;
  79021. (function (BABYLON) {
  79022. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79023. __extends(DisplayPassPostProcess, _super);
  79024. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79025. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79026. }
  79027. return DisplayPassPostProcess;
  79028. }(BABYLON.PostProcess));
  79029. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79030. })(BABYLON || (BABYLON = {}));
  79031. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79032. var BABYLON;
  79033. (function (BABYLON) {
  79034. var HighlightsPostProcess = /** @class */ (function (_super) {
  79035. __extends(HighlightsPostProcess, _super);
  79036. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79037. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79038. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79039. }
  79040. return HighlightsPostProcess;
  79041. }(BABYLON.PostProcess));
  79042. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79043. })(BABYLON || (BABYLON = {}));
  79044. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79045. var BABYLON;
  79046. (function (BABYLON) {
  79047. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79048. __extends(ImageProcessingPostProcess, _super);
  79049. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79050. if (camera === void 0) { camera = null; }
  79051. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79052. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79053. _this._fromLinearSpace = true;
  79054. /**
  79055. * Defines cache preventing GC.
  79056. */
  79057. _this._defines = {
  79058. IMAGEPROCESSING: false,
  79059. VIGNETTE: false,
  79060. VIGNETTEBLENDMODEMULTIPLY: false,
  79061. VIGNETTEBLENDMODEOPAQUE: false,
  79062. TONEMAPPING: false,
  79063. CONTRAST: false,
  79064. COLORCURVES: false,
  79065. COLORGRADING: false,
  79066. COLORGRADING3D: false,
  79067. FROMLINEARSPACE: false,
  79068. SAMPLER3DGREENDEPTH: false,
  79069. SAMPLER3DBGRMAP: false,
  79070. IMAGEPROCESSINGPOSTPROCESS: false,
  79071. EXPOSURE: false,
  79072. };
  79073. // Setup the configuration as forced by the constructor. This would then not force the
  79074. // scene materials output in linear space and let untouched the default forward pass.
  79075. if (imageProcessingConfiguration) {
  79076. imageProcessingConfiguration.applyByPostProcess = true;
  79077. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79078. // This will cause the shader to be compiled
  79079. _this.fromLinearSpace = false;
  79080. }
  79081. // Setup the default processing configuration to the scene.
  79082. else {
  79083. _this._attachImageProcessingConfiguration(null, true);
  79084. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79085. }
  79086. _this.onApply = function (effect) {
  79087. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79088. };
  79089. return _this;
  79090. }
  79091. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79092. /**
  79093. * Gets the image processing configuration used either in this material.
  79094. */
  79095. get: function () {
  79096. return this._imageProcessingConfiguration;
  79097. },
  79098. /**
  79099. * Sets the Default image processing configuration used either in the this material.
  79100. *
  79101. * If sets to null, the scene one is in use.
  79102. */
  79103. set: function (value) {
  79104. this._attachImageProcessingConfiguration(value);
  79105. },
  79106. enumerable: true,
  79107. configurable: true
  79108. });
  79109. /**
  79110. * Attaches a new image processing configuration to the PBR Material.
  79111. * @param configuration
  79112. */
  79113. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79114. var _this = this;
  79115. if (doNotBuild === void 0) { doNotBuild = false; }
  79116. if (configuration === this._imageProcessingConfiguration) {
  79117. return;
  79118. }
  79119. // Detaches observer.
  79120. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79121. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79122. }
  79123. // Pick the scene configuration if needed.
  79124. if (!configuration) {
  79125. var scene = null;
  79126. var engine = this.getEngine();
  79127. var camera = this.getCamera();
  79128. if (camera) {
  79129. scene = camera.getScene();
  79130. }
  79131. else if (engine && engine.scenes) {
  79132. var scenes = engine.scenes;
  79133. scene = scenes[scenes.length - 1];
  79134. }
  79135. else {
  79136. scene = BABYLON.Engine.LastCreatedScene;
  79137. }
  79138. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79139. }
  79140. else {
  79141. this._imageProcessingConfiguration = configuration;
  79142. }
  79143. // Attaches observer.
  79144. if (this._imageProcessingConfiguration) {
  79145. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79146. _this._updateParameters();
  79147. });
  79148. }
  79149. // Ensure the effect will be rebuilt.
  79150. if (!doNotBuild) {
  79151. this._updateParameters();
  79152. }
  79153. };
  79154. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79155. /**
  79156. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79157. */
  79158. get: function () {
  79159. return this.imageProcessingConfiguration.colorCurves;
  79160. },
  79161. /**
  79162. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79163. */
  79164. set: function (value) {
  79165. this.imageProcessingConfiguration.colorCurves = value;
  79166. },
  79167. enumerable: true,
  79168. configurable: true
  79169. });
  79170. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79171. /**
  79172. * Gets wether the color curves effect is enabled.
  79173. */
  79174. get: function () {
  79175. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79176. },
  79177. /**
  79178. * Sets wether the color curves effect is enabled.
  79179. */
  79180. set: function (value) {
  79181. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79182. },
  79183. enumerable: true,
  79184. configurable: true
  79185. });
  79186. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79187. /**
  79188. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79189. */
  79190. get: function () {
  79191. return this.imageProcessingConfiguration.colorGradingTexture;
  79192. },
  79193. /**
  79194. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79195. */
  79196. set: function (value) {
  79197. this.imageProcessingConfiguration.colorGradingTexture = value;
  79198. },
  79199. enumerable: true,
  79200. configurable: true
  79201. });
  79202. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79203. /**
  79204. * Gets wether the color grading effect is enabled.
  79205. */
  79206. get: function () {
  79207. return this.imageProcessingConfiguration.colorGradingEnabled;
  79208. },
  79209. /**
  79210. * Gets wether the color grading effect is enabled.
  79211. */
  79212. set: function (value) {
  79213. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79214. },
  79215. enumerable: true,
  79216. configurable: true
  79217. });
  79218. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79219. /**
  79220. * Gets exposure used in the effect.
  79221. */
  79222. get: function () {
  79223. return this.imageProcessingConfiguration.exposure;
  79224. },
  79225. /**
  79226. * Sets exposure used in the effect.
  79227. */
  79228. set: function (value) {
  79229. this.imageProcessingConfiguration.exposure = value;
  79230. },
  79231. enumerable: true,
  79232. configurable: true
  79233. });
  79234. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79235. /**
  79236. * Gets wether tonemapping is enabled or not.
  79237. */
  79238. get: function () {
  79239. return this._imageProcessingConfiguration.toneMappingEnabled;
  79240. },
  79241. /**
  79242. * Sets wether tonemapping is enabled or not
  79243. */
  79244. set: function (value) {
  79245. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79246. },
  79247. enumerable: true,
  79248. configurable: true
  79249. });
  79250. ;
  79251. ;
  79252. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79253. /**
  79254. * Gets contrast used in the effect.
  79255. */
  79256. get: function () {
  79257. return this.imageProcessingConfiguration.contrast;
  79258. },
  79259. /**
  79260. * Sets contrast used in the effect.
  79261. */
  79262. set: function (value) {
  79263. this.imageProcessingConfiguration.contrast = value;
  79264. },
  79265. enumerable: true,
  79266. configurable: true
  79267. });
  79268. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79269. /**
  79270. * Gets Vignette stretch size.
  79271. */
  79272. get: function () {
  79273. return this.imageProcessingConfiguration.vignetteStretch;
  79274. },
  79275. /**
  79276. * Sets Vignette stretch size.
  79277. */
  79278. set: function (value) {
  79279. this.imageProcessingConfiguration.vignetteStretch = value;
  79280. },
  79281. enumerable: true,
  79282. configurable: true
  79283. });
  79284. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79285. /**
  79286. * Gets Vignette centre X Offset.
  79287. */
  79288. get: function () {
  79289. return this.imageProcessingConfiguration.vignetteCentreX;
  79290. },
  79291. /**
  79292. * Sets Vignette centre X Offset.
  79293. */
  79294. set: function (value) {
  79295. this.imageProcessingConfiguration.vignetteCentreX = value;
  79296. },
  79297. enumerable: true,
  79298. configurable: true
  79299. });
  79300. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79301. /**
  79302. * Gets Vignette centre Y Offset.
  79303. */
  79304. get: function () {
  79305. return this.imageProcessingConfiguration.vignetteCentreY;
  79306. },
  79307. /**
  79308. * Sets Vignette centre Y Offset.
  79309. */
  79310. set: function (value) {
  79311. this.imageProcessingConfiguration.vignetteCentreY = value;
  79312. },
  79313. enumerable: true,
  79314. configurable: true
  79315. });
  79316. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79317. /**
  79318. * Gets Vignette weight or intensity of the vignette effect.
  79319. */
  79320. get: function () {
  79321. return this.imageProcessingConfiguration.vignetteWeight;
  79322. },
  79323. /**
  79324. * Sets Vignette weight or intensity of the vignette effect.
  79325. */
  79326. set: function (value) {
  79327. this.imageProcessingConfiguration.vignetteWeight = value;
  79328. },
  79329. enumerable: true,
  79330. configurable: true
  79331. });
  79332. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79333. /**
  79334. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79335. * if vignetteEnabled is set to true.
  79336. */
  79337. get: function () {
  79338. return this.imageProcessingConfiguration.vignetteColor;
  79339. },
  79340. /**
  79341. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79342. * if vignetteEnabled is set to true.
  79343. */
  79344. set: function (value) {
  79345. this.imageProcessingConfiguration.vignetteColor = value;
  79346. },
  79347. enumerable: true,
  79348. configurable: true
  79349. });
  79350. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79351. /**
  79352. * Gets Camera field of view used by the Vignette effect.
  79353. */
  79354. get: function () {
  79355. return this.imageProcessingConfiguration.vignetteCameraFov;
  79356. },
  79357. /**
  79358. * Sets Camera field of view used by the Vignette effect.
  79359. */
  79360. set: function (value) {
  79361. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79362. },
  79363. enumerable: true,
  79364. configurable: true
  79365. });
  79366. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79367. /**
  79368. * Gets the vignette blend mode allowing different kind of effect.
  79369. */
  79370. get: function () {
  79371. return this.imageProcessingConfiguration.vignetteBlendMode;
  79372. },
  79373. /**
  79374. * Sets the vignette blend mode allowing different kind of effect.
  79375. */
  79376. set: function (value) {
  79377. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79378. },
  79379. enumerable: true,
  79380. configurable: true
  79381. });
  79382. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79383. /**
  79384. * Gets wether the vignette effect is enabled.
  79385. */
  79386. get: function () {
  79387. return this.imageProcessingConfiguration.vignetteEnabled;
  79388. },
  79389. /**
  79390. * Sets wether the vignette effect is enabled.
  79391. */
  79392. set: function (value) {
  79393. this.imageProcessingConfiguration.vignetteEnabled = value;
  79394. },
  79395. enumerable: true,
  79396. configurable: true
  79397. });
  79398. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79399. /**
  79400. * Gets wether the input of the processing is in Gamma or Linear Space.
  79401. */
  79402. get: function () {
  79403. return this._fromLinearSpace;
  79404. },
  79405. /**
  79406. * Sets wether the input of the processing is in Gamma or Linear Space.
  79407. */
  79408. set: function (value) {
  79409. if (this._fromLinearSpace === value) {
  79410. return;
  79411. }
  79412. this._fromLinearSpace = value;
  79413. this._updateParameters();
  79414. },
  79415. enumerable: true,
  79416. configurable: true
  79417. });
  79418. ImageProcessingPostProcess.prototype.getClassName = function () {
  79419. return "ImageProcessingPostProcess";
  79420. };
  79421. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79422. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79423. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79424. var defines = "";
  79425. for (var define in this._defines) {
  79426. if (this._defines[define]) {
  79427. defines += "#define " + define + ";\r\n";
  79428. }
  79429. }
  79430. var samplers = ["textureSampler"];
  79431. var uniforms = ["scale"];
  79432. if (BABYLON.ImageProcessingConfiguration) {
  79433. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79434. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79435. }
  79436. this.updateEffect(defines, uniforms, samplers);
  79437. };
  79438. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79439. _super.prototype.dispose.call(this, camera);
  79440. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79441. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79442. }
  79443. if (this._imageProcessingConfiguration) {
  79444. this.imageProcessingConfiguration.applyByPostProcess = false;
  79445. }
  79446. };
  79447. __decorate([
  79448. BABYLON.serialize()
  79449. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79450. return ImageProcessingPostProcess;
  79451. }(BABYLON.PostProcess));
  79452. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79453. })(BABYLON || (BABYLON = {}));
  79454. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79455. var BABYLON;
  79456. (function (BABYLON) {
  79457. /**
  79458. * Class used to store bone information
  79459. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79460. */
  79461. var Bone = /** @class */ (function (_super) {
  79462. __extends(Bone, _super);
  79463. /**
  79464. * Create a new bone
  79465. * @param name defines the bone name
  79466. * @param skeleton defines the parent skeleton
  79467. * @param parentBone defines the parent (can be null if the bone is the root)
  79468. * @param localMatrix defines the local matrix
  79469. * @param restPose defines the rest pose matrix
  79470. * @param baseMatrix defines the base matrix
  79471. * @param index defines index of the bone in the hiearchy
  79472. */
  79473. function Bone(
  79474. /**
  79475. * defines the bone name
  79476. */
  79477. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79478. if (parentBone === void 0) { parentBone = null; }
  79479. if (localMatrix === void 0) { localMatrix = null; }
  79480. if (restPose === void 0) { restPose = null; }
  79481. if (baseMatrix === void 0) { baseMatrix = null; }
  79482. if (index === void 0) { index = null; }
  79483. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79484. _this.name = name;
  79485. /**
  79486. * Gets the list of child bones
  79487. */
  79488. _this.children = new Array();
  79489. /** Gets the animations associated with this bone */
  79490. _this.animations = new Array();
  79491. /**
  79492. * @hidden Internal only
  79493. * Set this value to map this bone to a different index in the transform matrices
  79494. * Set this value to -1 to exclude the bone from the transform matrices
  79495. */
  79496. _this._index = null;
  79497. _this._absoluteTransform = new BABYLON.Matrix();
  79498. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79499. _this._scalingDeterminant = 1;
  79500. _this._worldTransform = new BABYLON.Matrix();
  79501. _this._needToDecompose = true;
  79502. _this._needToCompose = false;
  79503. _this._skeleton = skeleton;
  79504. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79505. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79506. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79507. _this._index = index;
  79508. skeleton.bones.push(_this);
  79509. _this.setParent(parentBone, false);
  79510. if (baseMatrix || localMatrix) {
  79511. _this._updateDifferenceMatrix();
  79512. }
  79513. return _this;
  79514. }
  79515. Object.defineProperty(Bone.prototype, "_matrix", {
  79516. /** @hidden */
  79517. get: function () {
  79518. this._compose();
  79519. return this._localMatrix;
  79520. },
  79521. /** @hidden */
  79522. set: function (value) {
  79523. this._localMatrix.copyFrom(value);
  79524. this._needToDecompose = true;
  79525. },
  79526. enumerable: true,
  79527. configurable: true
  79528. });
  79529. // Members
  79530. /**
  79531. * Gets the parent skeleton
  79532. * @returns a skeleton
  79533. */
  79534. Bone.prototype.getSkeleton = function () {
  79535. return this._skeleton;
  79536. };
  79537. /**
  79538. * Gets parent bone
  79539. * @returns a bone or null if the bone is the root of the bone hierarchy
  79540. */
  79541. Bone.prototype.getParent = function () {
  79542. return this._parent;
  79543. };
  79544. /**
  79545. * Sets the parent bone
  79546. * @param parent defines the parent (can be null if the bone is the root)
  79547. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79548. */
  79549. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79550. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79551. if (this._parent === parent) {
  79552. return;
  79553. }
  79554. if (this._parent) {
  79555. var index = this._parent.children.indexOf(this);
  79556. if (index !== -1) {
  79557. this._parent.children.splice(index, 1);
  79558. }
  79559. }
  79560. this._parent = parent;
  79561. if (this._parent) {
  79562. this._parent.children.push(this);
  79563. }
  79564. if (updateDifferenceMatrix) {
  79565. this._updateDifferenceMatrix();
  79566. }
  79567. this.markAsDirty();
  79568. };
  79569. /**
  79570. * Gets the local matrix
  79571. * @returns a matrix
  79572. */
  79573. Bone.prototype.getLocalMatrix = function () {
  79574. this._compose();
  79575. return this._localMatrix;
  79576. };
  79577. /**
  79578. * Gets the base matrix (initial matrix which remains unchanged)
  79579. * @returns a matrix
  79580. */
  79581. Bone.prototype.getBaseMatrix = function () {
  79582. return this._baseMatrix;
  79583. };
  79584. /**
  79585. * Gets the rest pose matrix
  79586. * @returns a matrix
  79587. */
  79588. Bone.prototype.getRestPose = function () {
  79589. return this._restPose;
  79590. };
  79591. /**
  79592. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79593. */
  79594. Bone.prototype.getWorldMatrix = function () {
  79595. return this._worldTransform;
  79596. };
  79597. /**
  79598. * Sets the local matrix to rest pose matrix
  79599. */
  79600. Bone.prototype.returnToRest = function () {
  79601. this.updateMatrix(this._restPose.clone());
  79602. };
  79603. /**
  79604. * Gets the inverse of the absolute transform matrix.
  79605. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79606. * @returns a matrix
  79607. */
  79608. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79609. return this._invertedAbsoluteTransform;
  79610. };
  79611. /**
  79612. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79613. * @returns a matrix
  79614. */
  79615. Bone.prototype.getAbsoluteTransform = function () {
  79616. return this._absoluteTransform;
  79617. };
  79618. Object.defineProperty(Bone.prototype, "position", {
  79619. // Properties (matches AbstractMesh properties)
  79620. /** Gets or sets current position (in local space) */
  79621. get: function () {
  79622. this._decompose();
  79623. return this._localPosition;
  79624. },
  79625. set: function (newPosition) {
  79626. this._decompose();
  79627. this._localPosition.copyFrom(newPosition);
  79628. this._markAsDirtyAndCompose();
  79629. },
  79630. enumerable: true,
  79631. configurable: true
  79632. });
  79633. Object.defineProperty(Bone.prototype, "rotation", {
  79634. /** Gets or sets current rotation (in local space) */
  79635. get: function () {
  79636. return this.getRotation();
  79637. },
  79638. set: function (newRotation) {
  79639. this.setRotation(newRotation);
  79640. },
  79641. enumerable: true,
  79642. configurable: true
  79643. });
  79644. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79645. /** Gets or sets current rotation quaternion (in local space) */
  79646. get: function () {
  79647. this._decompose();
  79648. return this._localRotation;
  79649. },
  79650. set: function (newRotation) {
  79651. this.setRotationQuaternion(newRotation);
  79652. },
  79653. enumerable: true,
  79654. configurable: true
  79655. });
  79656. Object.defineProperty(Bone.prototype, "scaling", {
  79657. /** Gets or sets current scaling (in local space) */
  79658. get: function () {
  79659. return this.getScale();
  79660. },
  79661. set: function (newScaling) {
  79662. this.setScale(newScaling);
  79663. },
  79664. enumerable: true,
  79665. configurable: true
  79666. });
  79667. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79668. /**
  79669. * Gets the animation properties override
  79670. */
  79671. get: function () {
  79672. return this._skeleton.animationPropertiesOverride;
  79673. },
  79674. enumerable: true,
  79675. configurable: true
  79676. });
  79677. // Methods
  79678. Bone.prototype._decompose = function () {
  79679. if (!this._needToDecompose) {
  79680. return;
  79681. }
  79682. this._needToDecompose = false;
  79683. if (!this._localScaling) {
  79684. this._localScaling = BABYLON.Vector3.Zero();
  79685. this._localRotation = BABYLON.Quaternion.Zero();
  79686. this._localPosition = BABYLON.Vector3.Zero();
  79687. }
  79688. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79689. };
  79690. Bone.prototype._compose = function () {
  79691. if (!this._needToCompose) {
  79692. return;
  79693. }
  79694. this._needToCompose = false;
  79695. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79696. };
  79697. /**
  79698. * Update the base and local matrices
  79699. * @param matrix defines the new base or local matrix
  79700. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79701. * @param updateLocalMatrix defines if the local matrix should be updated
  79702. */
  79703. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79704. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79705. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79706. this._baseMatrix.copyFrom(matrix);
  79707. if (updateDifferenceMatrix) {
  79708. this._updateDifferenceMatrix();
  79709. }
  79710. if (updateLocalMatrix) {
  79711. this._localMatrix.copyFrom(matrix);
  79712. this._markAsDirtyAndDecompose();
  79713. }
  79714. else {
  79715. this.markAsDirty();
  79716. }
  79717. };
  79718. /** @hidden */
  79719. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79720. if (updateChildren === void 0) { updateChildren = true; }
  79721. if (!rootMatrix) {
  79722. rootMatrix = this._baseMatrix;
  79723. }
  79724. if (this._parent) {
  79725. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79726. }
  79727. else {
  79728. this._absoluteTransform.copyFrom(rootMatrix);
  79729. }
  79730. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79731. if (updateChildren) {
  79732. for (var index = 0; index < this.children.length; index++) {
  79733. this.children[index]._updateDifferenceMatrix();
  79734. }
  79735. }
  79736. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79737. };
  79738. /**
  79739. * Flag the bone as dirty (Forcing it to update everything)
  79740. */
  79741. Bone.prototype.markAsDirty = function () {
  79742. this._currentRenderId++;
  79743. this._childRenderId++;
  79744. this._skeleton._markAsDirty();
  79745. };
  79746. Bone.prototype._markAsDirtyAndCompose = function () {
  79747. this.markAsDirty();
  79748. this._needToCompose = true;
  79749. };
  79750. Bone.prototype._markAsDirtyAndDecompose = function () {
  79751. this.markAsDirty();
  79752. this._needToDecompose = true;
  79753. };
  79754. /**
  79755. * Copy an animation range from another bone
  79756. * @param source defines the source bone
  79757. * @param rangeName defines the range name to copy
  79758. * @param frameOffset defines the frame offset
  79759. * @param rescaleAsRequired defines if rescaling must be applied if required
  79760. * @param skelDimensionsRatio defines the scaling ratio
  79761. * @returns true if operation was successful
  79762. */
  79763. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79764. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79765. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79766. // all animation may be coming from a library skeleton, so may need to create animation
  79767. if (this.animations.length === 0) {
  79768. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79769. this.animations[0].setKeys([]);
  79770. }
  79771. // get animation info / verify there is such a range from the source bone
  79772. var sourceRange = source.animations[0].getRange(rangeName);
  79773. if (!sourceRange) {
  79774. return false;
  79775. }
  79776. var from = sourceRange.from;
  79777. var to = sourceRange.to;
  79778. var sourceKeys = source.animations[0].getKeys();
  79779. // rescaling prep
  79780. var sourceBoneLength = source.length;
  79781. var sourceParent = source.getParent();
  79782. var parent = this.getParent();
  79783. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79784. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79785. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79786. var destKeys = this.animations[0].getKeys();
  79787. // loop vars declaration
  79788. var orig;
  79789. var origTranslation;
  79790. var mat;
  79791. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79792. orig = sourceKeys[key];
  79793. if (orig.frame >= from && orig.frame <= to) {
  79794. if (rescaleAsRequired) {
  79795. mat = orig.value.clone();
  79796. // scale based on parent ratio, when bone has parent
  79797. if (parentScalingReqd) {
  79798. origTranslation = mat.getTranslation();
  79799. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79800. // scale based on skeleton dimension ratio when root bone, and value is passed
  79801. }
  79802. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79803. origTranslation = mat.getTranslation();
  79804. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79805. // use original when root bone, and no data for skelDimensionsRatio
  79806. }
  79807. else {
  79808. mat = orig.value;
  79809. }
  79810. }
  79811. else {
  79812. mat = orig.value;
  79813. }
  79814. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79815. }
  79816. }
  79817. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79818. return true;
  79819. };
  79820. /**
  79821. * Translate the bone in local or world space
  79822. * @param vec The amount to translate the bone
  79823. * @param space The space that the translation is in
  79824. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79825. */
  79826. Bone.prototype.translate = function (vec, space, mesh) {
  79827. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79828. var lm = this.getLocalMatrix();
  79829. if (space == BABYLON.Space.LOCAL) {
  79830. lm.m[12] += vec.x;
  79831. lm.m[13] += vec.y;
  79832. lm.m[14] += vec.z;
  79833. }
  79834. else {
  79835. var wm = null;
  79836. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79837. if (mesh) {
  79838. wm = mesh.getWorldMatrix();
  79839. }
  79840. this._skeleton.computeAbsoluteTransforms();
  79841. var tmat = Bone._tmpMats[0];
  79842. var tvec = Bone._tmpVecs[0];
  79843. if (this._parent) {
  79844. if (mesh && wm) {
  79845. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79846. tmat.multiplyToRef(wm, tmat);
  79847. }
  79848. else {
  79849. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79850. }
  79851. }
  79852. tmat.m[12] = 0;
  79853. tmat.m[13] = 0;
  79854. tmat.m[14] = 0;
  79855. tmat.invert();
  79856. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79857. lm.m[12] += tvec.x;
  79858. lm.m[13] += tvec.y;
  79859. lm.m[14] += tvec.z;
  79860. }
  79861. this._markAsDirtyAndDecompose();
  79862. };
  79863. /**
  79864. * Set the postion of the bone in local or world space
  79865. * @param position The position to set the bone
  79866. * @param space The space that the position is in
  79867. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79868. */
  79869. Bone.prototype.setPosition = function (position, space, mesh) {
  79870. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79871. var lm = this.getLocalMatrix();
  79872. if (space == BABYLON.Space.LOCAL) {
  79873. lm.m[12] = position.x;
  79874. lm.m[13] = position.y;
  79875. lm.m[14] = position.z;
  79876. }
  79877. else {
  79878. var wm = null;
  79879. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79880. if (mesh) {
  79881. wm = mesh.getWorldMatrix();
  79882. }
  79883. this._skeleton.computeAbsoluteTransforms();
  79884. var tmat = Bone._tmpMats[0];
  79885. var vec = Bone._tmpVecs[0];
  79886. if (this._parent) {
  79887. if (mesh && wm) {
  79888. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79889. tmat.multiplyToRef(wm, tmat);
  79890. }
  79891. else {
  79892. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79893. }
  79894. }
  79895. tmat.invert();
  79896. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79897. lm.m[12] = vec.x;
  79898. lm.m[13] = vec.y;
  79899. lm.m[14] = vec.z;
  79900. }
  79901. this._markAsDirtyAndDecompose();
  79902. };
  79903. /**
  79904. * Set the absolute position of the bone (world space)
  79905. * @param position The position to set the bone
  79906. * @param mesh The mesh that this bone is attached to
  79907. */
  79908. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79909. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79910. };
  79911. /**
  79912. * Scale the bone on the x, y and z axes (in local space)
  79913. * @param x The amount to scale the bone on the x axis
  79914. * @param y The amount to scale the bone on the y axis
  79915. * @param z The amount to scale the bone on the z axis
  79916. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79917. */
  79918. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79919. if (scaleChildren === void 0) { scaleChildren = false; }
  79920. var locMat = this.getLocalMatrix();
  79921. // Apply new scaling on top of current local matrix
  79922. var scaleMat = Bone._tmpMats[0];
  79923. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79924. scaleMat.multiplyToRef(locMat, locMat);
  79925. // Invert scaling matrix and apply the inverse to all children
  79926. scaleMat.invert();
  79927. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79928. var child = _a[_i];
  79929. var cm = child.getLocalMatrix();
  79930. cm.multiplyToRef(scaleMat, cm);
  79931. cm.m[12] *= x;
  79932. cm.m[13] *= y;
  79933. cm.m[14] *= z;
  79934. child._markAsDirtyAndDecompose();
  79935. }
  79936. this._markAsDirtyAndDecompose();
  79937. if (scaleChildren) {
  79938. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79939. var child = _c[_b];
  79940. child.scale(x, y, z, scaleChildren);
  79941. }
  79942. }
  79943. };
  79944. /**
  79945. * Set the bone scaling in local space
  79946. * @param scale defines the scaling vector
  79947. */
  79948. Bone.prototype.setScale = function (scale) {
  79949. this._decompose();
  79950. this._localScaling.copyFrom(scale);
  79951. this._markAsDirtyAndCompose();
  79952. };
  79953. /**
  79954. * Gets the current scaling in local space
  79955. * @returns the current scaling vector
  79956. */
  79957. Bone.prototype.getScale = function () {
  79958. this._decompose();
  79959. return this._localScaling;
  79960. };
  79961. /**
  79962. * Gets the current scaling in local space and stores it in a target vector
  79963. * @param result defines the target vector
  79964. */
  79965. Bone.prototype.getScaleToRef = function (result) {
  79966. this._decompose();
  79967. result.copyFrom(this._localScaling);
  79968. };
  79969. /**
  79970. * Set the yaw, pitch, and roll of the bone in local or world space
  79971. * @param yaw The rotation of the bone on the y axis
  79972. * @param pitch The rotation of the bone on the x axis
  79973. * @param roll The rotation of the bone on the z axis
  79974. * @param space The space that the axes of rotation are in
  79975. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79976. */
  79977. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79979. if (space === BABYLON.Space.LOCAL) {
  79980. var quat = Bone._tmpQuat;
  79981. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79982. this.setRotationQuaternion(quat, space, mesh);
  79983. return;
  79984. }
  79985. var rotMatInv = Bone._tmpMats[0];
  79986. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79987. return;
  79988. }
  79989. var rotMat = Bone._tmpMats[1];
  79990. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79991. rotMatInv.multiplyToRef(rotMat, rotMat);
  79992. this._rotateWithMatrix(rotMat, space, mesh);
  79993. };
  79994. /**
  79995. * Add a rotation to the bone on an axis in local or world space
  79996. * @param axis The axis to rotate the bone on
  79997. * @param amount The amount to rotate the bone
  79998. * @param space The space that the axis is in
  79999. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80000. */
  80001. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80003. var rmat = Bone._tmpMats[0];
  80004. rmat.m[12] = 0;
  80005. rmat.m[13] = 0;
  80006. rmat.m[14] = 0;
  80007. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80008. this._rotateWithMatrix(rmat, space, mesh);
  80009. };
  80010. /**
  80011. * Set the rotation of the bone to a particular axis angle in local or world space
  80012. * @param axis The axis to rotate the bone on
  80013. * @param angle The angle that the bone should be rotated to
  80014. * @param space The space that the axis is in
  80015. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80016. */
  80017. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80018. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80019. if (space === BABYLON.Space.LOCAL) {
  80020. var quat = Bone._tmpQuat;
  80021. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80022. this.setRotationQuaternion(quat, space, mesh);
  80023. return;
  80024. }
  80025. var rotMatInv = Bone._tmpMats[0];
  80026. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80027. return;
  80028. }
  80029. var rotMat = Bone._tmpMats[1];
  80030. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80031. rotMatInv.multiplyToRef(rotMat, rotMat);
  80032. this._rotateWithMatrix(rotMat, space, mesh);
  80033. };
  80034. /**
  80035. * Set the euler rotation of the bone in local of world space
  80036. * @param rotation The euler rotation that the bone should be set to
  80037. * @param space The space that the rotation is in
  80038. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80039. */
  80040. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80042. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80043. };
  80044. /**
  80045. * Set the quaternion rotation of the bone in local of world space
  80046. * @param quat The quaternion rotation that the bone should be set to
  80047. * @param space The space that the rotation is in
  80048. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80049. */
  80050. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80051. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80052. if (space === BABYLON.Space.LOCAL) {
  80053. this._decompose();
  80054. this._localRotation.copyFrom(quat);
  80055. this._markAsDirtyAndCompose();
  80056. return;
  80057. }
  80058. var rotMatInv = Bone._tmpMats[0];
  80059. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80060. return;
  80061. }
  80062. var rotMat = Bone._tmpMats[1];
  80063. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80064. rotMatInv.multiplyToRef(rotMat, rotMat);
  80065. this._rotateWithMatrix(rotMat, space, mesh);
  80066. };
  80067. /**
  80068. * Set the rotation matrix of the bone in local of world space
  80069. * @param rotMat The rotation matrix that the bone should be set to
  80070. * @param space The space that the rotation is in
  80071. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80072. */
  80073. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80074. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80075. if (space === BABYLON.Space.LOCAL) {
  80076. var quat = Bone._tmpQuat;
  80077. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80078. this.setRotationQuaternion(quat, space, mesh);
  80079. return;
  80080. }
  80081. var rotMatInv = Bone._tmpMats[0];
  80082. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80083. return;
  80084. }
  80085. var rotMat2 = Bone._tmpMats[1];
  80086. rotMat2.copyFrom(rotMat);
  80087. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80088. this._rotateWithMatrix(rotMat2, space, mesh);
  80089. };
  80090. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80092. var lmat = this.getLocalMatrix();
  80093. var lx = lmat.m[12];
  80094. var ly = lmat.m[13];
  80095. var lz = lmat.m[14];
  80096. var parent = this.getParent();
  80097. var parentScale = Bone._tmpMats[3];
  80098. var parentScaleInv = Bone._tmpMats[4];
  80099. if (parent && space == BABYLON.Space.WORLD) {
  80100. if (mesh) {
  80101. parentScale.copyFrom(mesh.getWorldMatrix());
  80102. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80103. }
  80104. else {
  80105. parentScale.copyFrom(parent.getAbsoluteTransform());
  80106. }
  80107. parentScaleInv.copyFrom(parentScale);
  80108. parentScaleInv.invert();
  80109. lmat.multiplyToRef(parentScale, lmat);
  80110. lmat.multiplyToRef(rmat, lmat);
  80111. lmat.multiplyToRef(parentScaleInv, lmat);
  80112. }
  80113. else {
  80114. if (space == BABYLON.Space.WORLD && mesh) {
  80115. parentScale.copyFrom(mesh.getWorldMatrix());
  80116. parentScaleInv.copyFrom(parentScale);
  80117. parentScaleInv.invert();
  80118. lmat.multiplyToRef(parentScale, lmat);
  80119. lmat.multiplyToRef(rmat, lmat);
  80120. lmat.multiplyToRef(parentScaleInv, lmat);
  80121. }
  80122. else {
  80123. lmat.multiplyToRef(rmat, lmat);
  80124. }
  80125. }
  80126. lmat.m[12] = lx;
  80127. lmat.m[13] = ly;
  80128. lmat.m[14] = lz;
  80129. this.computeAbsoluteTransforms();
  80130. this._markAsDirtyAndDecompose();
  80131. };
  80132. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80133. var scaleMatrix = Bone._tmpMats[2];
  80134. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80135. if (mesh) {
  80136. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80137. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80138. }
  80139. rotMatInv.invert();
  80140. if (isNaN(rotMatInv.m[0])) {
  80141. // Matrix failed to invert.
  80142. // This can happen if scale is zero for example.
  80143. return false;
  80144. }
  80145. scaleMatrix.m[0] *= this._scalingDeterminant;
  80146. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80147. return true;
  80148. };
  80149. /**
  80150. * Get the position of the bone in local or world space
  80151. * @param space The space that the returned position is in
  80152. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80153. * @returns The position of the bone
  80154. */
  80155. Bone.prototype.getPosition = function (space, mesh) {
  80156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80157. if (mesh === void 0) { mesh = null; }
  80158. var pos = BABYLON.Vector3.Zero();
  80159. this.getPositionToRef(space, mesh, pos);
  80160. return pos;
  80161. };
  80162. /**
  80163. * Copy the position of the bone to a vector3 in local or world space
  80164. * @param space The space that the returned position is in
  80165. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80166. * @param result The vector3 to copy the position to
  80167. */
  80168. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80169. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80170. if (space == BABYLON.Space.LOCAL) {
  80171. var lm = this.getLocalMatrix();
  80172. result.x = lm.m[12];
  80173. result.y = lm.m[13];
  80174. result.z = lm.m[14];
  80175. }
  80176. else {
  80177. var wm = null;
  80178. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80179. if (mesh) {
  80180. wm = mesh.getWorldMatrix();
  80181. }
  80182. this._skeleton.computeAbsoluteTransforms();
  80183. var tmat = Bone._tmpMats[0];
  80184. if (mesh && wm) {
  80185. tmat.copyFrom(this.getAbsoluteTransform());
  80186. tmat.multiplyToRef(wm, tmat);
  80187. }
  80188. else {
  80189. tmat = this.getAbsoluteTransform();
  80190. }
  80191. result.x = tmat.m[12];
  80192. result.y = tmat.m[13];
  80193. result.z = tmat.m[14];
  80194. }
  80195. };
  80196. /**
  80197. * Get the absolute position of the bone (world space)
  80198. * @param mesh The mesh that this bone is attached to
  80199. * @returns The absolute position of the bone
  80200. */
  80201. Bone.prototype.getAbsolutePosition = function (mesh) {
  80202. if (mesh === void 0) { mesh = null; }
  80203. var pos = BABYLON.Vector3.Zero();
  80204. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80205. return pos;
  80206. };
  80207. /**
  80208. * Copy the absolute position of the bone (world space) to the result param
  80209. * @param mesh The mesh that this bone is attached to
  80210. * @param result The vector3 to copy the absolute position to
  80211. */
  80212. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80213. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80214. };
  80215. /**
  80216. * Compute the absolute transforms of this bone and its children
  80217. */
  80218. Bone.prototype.computeAbsoluteTransforms = function () {
  80219. this._compose();
  80220. if (this._parent) {
  80221. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80222. }
  80223. else {
  80224. this._absoluteTransform.copyFrom(this._localMatrix);
  80225. var poseMatrix = this._skeleton.getPoseMatrix();
  80226. if (poseMatrix) {
  80227. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80228. }
  80229. }
  80230. var children = this.children;
  80231. var len = children.length;
  80232. for (var i = 0; i < len; i++) {
  80233. children[i].computeAbsoluteTransforms();
  80234. }
  80235. };
  80236. /**
  80237. * Get the world direction from an axis that is in the local space of the bone
  80238. * @param localAxis The local direction that is used to compute the world direction
  80239. * @param mesh The mesh that this bone is attached to
  80240. * @returns The world direction
  80241. */
  80242. Bone.prototype.getDirection = function (localAxis, mesh) {
  80243. if (mesh === void 0) { mesh = null; }
  80244. var result = BABYLON.Vector3.Zero();
  80245. this.getDirectionToRef(localAxis, mesh, result);
  80246. return result;
  80247. };
  80248. /**
  80249. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80250. * @param localAxis The local direction that is used to compute the world direction
  80251. * @param mesh The mesh that this bone is attached to
  80252. * @param result The vector3 that the world direction will be copied to
  80253. */
  80254. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80255. if (mesh === void 0) { mesh = null; }
  80256. var wm = null;
  80257. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80258. if (mesh) {
  80259. wm = mesh.getWorldMatrix();
  80260. }
  80261. this._skeleton.computeAbsoluteTransforms();
  80262. var mat = Bone._tmpMats[0];
  80263. mat.copyFrom(this.getAbsoluteTransform());
  80264. if (mesh && wm) {
  80265. mat.multiplyToRef(wm, mat);
  80266. }
  80267. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80268. result.normalize();
  80269. };
  80270. /**
  80271. * Get the euler rotation of the bone in local or world space
  80272. * @param space The space that the rotation should be in
  80273. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80274. * @returns The euler rotation
  80275. */
  80276. Bone.prototype.getRotation = function (space, mesh) {
  80277. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80278. if (mesh === void 0) { mesh = null; }
  80279. var result = BABYLON.Vector3.Zero();
  80280. this.getRotationToRef(space, mesh, result);
  80281. return result;
  80282. };
  80283. /**
  80284. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80285. * @param space The space that the rotation should be in
  80286. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80287. * @param result The vector3 that the rotation should be copied to
  80288. */
  80289. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80291. if (mesh === void 0) { mesh = null; }
  80292. var quat = Bone._tmpQuat;
  80293. this.getRotationQuaternionToRef(space, mesh, quat);
  80294. quat.toEulerAnglesToRef(result);
  80295. };
  80296. /**
  80297. * Get the quaternion rotation of the bone in either local or world space
  80298. * @param space The space that the rotation should be in
  80299. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80300. * @returns The quaternion rotation
  80301. */
  80302. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80304. if (mesh === void 0) { mesh = null; }
  80305. var result = BABYLON.Quaternion.Identity();
  80306. this.getRotationQuaternionToRef(space, mesh, result);
  80307. return result;
  80308. };
  80309. /**
  80310. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80311. * @param space The space that the rotation should be in
  80312. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80313. * @param result The quaternion that the rotation should be copied to
  80314. */
  80315. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80316. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80317. if (mesh === void 0) { mesh = null; }
  80318. if (space == BABYLON.Space.LOCAL) {
  80319. this._decompose();
  80320. result.copyFrom(this._localRotation);
  80321. }
  80322. else {
  80323. var mat = Bone._tmpMats[0];
  80324. var amat = this.getAbsoluteTransform();
  80325. if (mesh) {
  80326. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80327. }
  80328. else {
  80329. mat.copyFrom(amat);
  80330. }
  80331. mat.m[0] *= this._scalingDeterminant;
  80332. mat.m[1] *= this._scalingDeterminant;
  80333. mat.m[2] *= this._scalingDeterminant;
  80334. mat.decompose(undefined, result, undefined);
  80335. }
  80336. };
  80337. /**
  80338. * Get the rotation matrix of the bone in local or world space
  80339. * @param space The space that the rotation should be in
  80340. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80341. * @returns The rotation matrix
  80342. */
  80343. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80344. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80345. var result = BABYLON.Matrix.Identity();
  80346. this.getRotationMatrixToRef(space, mesh, result);
  80347. return result;
  80348. };
  80349. /**
  80350. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80351. * @param space The space that the rotation should be in
  80352. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80353. * @param result The quaternion that the rotation should be copied to
  80354. */
  80355. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80356. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80357. if (space == BABYLON.Space.LOCAL) {
  80358. this.getLocalMatrix().getRotationMatrixToRef(result);
  80359. }
  80360. else {
  80361. var mat = Bone._tmpMats[0];
  80362. var amat = this.getAbsoluteTransform();
  80363. if (mesh) {
  80364. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80365. }
  80366. else {
  80367. mat.copyFrom(amat);
  80368. }
  80369. mat.m[0] *= this._scalingDeterminant;
  80370. mat.m[1] *= this._scalingDeterminant;
  80371. mat.m[2] *= this._scalingDeterminant;
  80372. mat.getRotationMatrixToRef(result);
  80373. }
  80374. };
  80375. /**
  80376. * Get the world position of a point that is in the local space of the bone
  80377. * @param position The local position
  80378. * @param mesh The mesh that this bone is attached to
  80379. * @returns The world position
  80380. */
  80381. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80382. if (mesh === void 0) { mesh = null; }
  80383. var result = BABYLON.Vector3.Zero();
  80384. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80385. return result;
  80386. };
  80387. /**
  80388. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80389. * @param position The local position
  80390. * @param mesh The mesh that this bone is attached to
  80391. * @param result The vector3 that the world position should be copied to
  80392. */
  80393. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80394. if (mesh === void 0) { mesh = null; }
  80395. var wm = null;
  80396. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80397. if (mesh) {
  80398. wm = mesh.getWorldMatrix();
  80399. }
  80400. this._skeleton.computeAbsoluteTransforms();
  80401. var tmat = Bone._tmpMats[0];
  80402. if (mesh && wm) {
  80403. tmat.copyFrom(this.getAbsoluteTransform());
  80404. tmat.multiplyToRef(wm, tmat);
  80405. }
  80406. else {
  80407. tmat = this.getAbsoluteTransform();
  80408. }
  80409. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80410. };
  80411. /**
  80412. * Get the local position of a point that is in world space
  80413. * @param position The world position
  80414. * @param mesh The mesh that this bone is attached to
  80415. * @returns The local position
  80416. */
  80417. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80418. if (mesh === void 0) { mesh = null; }
  80419. var result = BABYLON.Vector3.Zero();
  80420. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80421. return result;
  80422. };
  80423. /**
  80424. * Get the local position of a point that is in world space and copy it to the result param
  80425. * @param position The world position
  80426. * @param mesh The mesh that this bone is attached to
  80427. * @param result The vector3 that the local position should be copied to
  80428. */
  80429. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80430. if (mesh === void 0) { mesh = null; }
  80431. var wm = null;
  80432. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80433. if (mesh) {
  80434. wm = mesh.getWorldMatrix();
  80435. }
  80436. this._skeleton.computeAbsoluteTransforms();
  80437. var tmat = Bone._tmpMats[0];
  80438. tmat.copyFrom(this.getAbsoluteTransform());
  80439. if (mesh && wm) {
  80440. tmat.multiplyToRef(wm, tmat);
  80441. }
  80442. tmat.invert();
  80443. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80444. };
  80445. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80446. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80447. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80448. return Bone;
  80449. }(BABYLON.Node));
  80450. BABYLON.Bone = Bone;
  80451. })(BABYLON || (BABYLON = {}));
  80452. //# sourceMappingURL=babylon.bone.js.map
  80453. var BABYLON;
  80454. (function (BABYLON) {
  80455. /**
  80456. * Class used to apply inverse kinematics to bones
  80457. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80458. */
  80459. var BoneIKController = /** @class */ (function () {
  80460. /**
  80461. * Creates a new BoneIKController
  80462. * @param mesh defines the mesh to control
  80463. * @param bone defines the bone to control
  80464. * @param options defines options to set up the controller
  80465. */
  80466. function BoneIKController(mesh, bone, options) {
  80467. /**
  80468. * Gets or sets the target position
  80469. */
  80470. this.targetPosition = BABYLON.Vector3.Zero();
  80471. /**
  80472. * Gets or sets the pole target position
  80473. */
  80474. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80475. /**
  80476. * Gets or sets the pole target local offset
  80477. */
  80478. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80479. /**
  80480. * Gets or sets the pole angle
  80481. */
  80482. this.poleAngle = 0;
  80483. /**
  80484. * 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)
  80485. */
  80486. this.slerpAmount = 1;
  80487. this._bone1Quat = BABYLON.Quaternion.Identity();
  80488. this._bone1Mat = BABYLON.Matrix.Identity();
  80489. this._bone2Ang = Math.PI;
  80490. this._maxAngle = Math.PI;
  80491. this._rightHandedSystem = false;
  80492. this._bendAxis = BABYLON.Vector3.Right();
  80493. this._slerping = false;
  80494. this._adjustRoll = 0;
  80495. this._bone2 = bone;
  80496. this._bone1 = bone.getParent();
  80497. if (!this._bone1) {
  80498. return;
  80499. }
  80500. this.mesh = mesh;
  80501. var bonePos = bone.getPosition();
  80502. if (bone.getAbsoluteTransform().determinant() > 0) {
  80503. this._rightHandedSystem = true;
  80504. this._bendAxis.x = 0;
  80505. this._bendAxis.y = 0;
  80506. this._bendAxis.z = -1;
  80507. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80508. this._adjustRoll = Math.PI * .5;
  80509. this._bendAxis.z = 1;
  80510. }
  80511. }
  80512. if (this._bone1.length) {
  80513. var boneScale1 = this._bone1.getScale();
  80514. var boneScale2 = this._bone2.getScale();
  80515. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80516. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80517. }
  80518. else if (this._bone1.children[0]) {
  80519. mesh.computeWorldMatrix(true);
  80520. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80521. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80522. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80523. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80524. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80525. }
  80526. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80527. this.maxAngle = Math.PI;
  80528. if (options) {
  80529. if (options.targetMesh) {
  80530. this.targetMesh = options.targetMesh;
  80531. this.targetMesh.computeWorldMatrix(true);
  80532. }
  80533. if (options.poleTargetMesh) {
  80534. this.poleTargetMesh = options.poleTargetMesh;
  80535. this.poleTargetMesh.computeWorldMatrix(true);
  80536. }
  80537. else if (options.poleTargetBone) {
  80538. this.poleTargetBone = options.poleTargetBone;
  80539. }
  80540. else if (this._bone1.getParent()) {
  80541. this.poleTargetBone = this._bone1.getParent();
  80542. }
  80543. if (options.poleTargetLocalOffset) {
  80544. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80545. }
  80546. if (options.poleAngle) {
  80547. this.poleAngle = options.poleAngle;
  80548. }
  80549. if (options.bendAxis) {
  80550. this._bendAxis.copyFrom(options.bendAxis);
  80551. }
  80552. if (options.maxAngle) {
  80553. this.maxAngle = options.maxAngle;
  80554. }
  80555. if (options.slerpAmount) {
  80556. this.slerpAmount = options.slerpAmount;
  80557. }
  80558. }
  80559. }
  80560. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80561. /**
  80562. * Gets or sets maximum allowed angle
  80563. */
  80564. get: function () {
  80565. return this._maxAngle;
  80566. },
  80567. set: function (value) {
  80568. this._setMaxAngle(value);
  80569. },
  80570. enumerable: true,
  80571. configurable: true
  80572. });
  80573. BoneIKController.prototype._setMaxAngle = function (ang) {
  80574. if (ang < 0) {
  80575. ang = 0;
  80576. }
  80577. if (ang > Math.PI || ang == undefined) {
  80578. ang = Math.PI;
  80579. }
  80580. this._maxAngle = ang;
  80581. var a = this._bone1Length;
  80582. var b = this._bone2Length;
  80583. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80584. };
  80585. /**
  80586. * Force the controller to update the bones
  80587. */
  80588. BoneIKController.prototype.update = function () {
  80589. var bone1 = this._bone1;
  80590. if (!bone1) {
  80591. return;
  80592. }
  80593. var target = this.targetPosition;
  80594. var poleTarget = this.poleTargetPosition;
  80595. var mat1 = BoneIKController._tmpMats[0];
  80596. var mat2 = BoneIKController._tmpMats[1];
  80597. if (this.targetMesh) {
  80598. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80599. }
  80600. if (this.poleTargetBone) {
  80601. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80602. }
  80603. else if (this.poleTargetMesh) {
  80604. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80605. }
  80606. var bonePos = BoneIKController._tmpVecs[0];
  80607. var zaxis = BoneIKController._tmpVecs[1];
  80608. var xaxis = BoneIKController._tmpVecs[2];
  80609. var yaxis = BoneIKController._tmpVecs[3];
  80610. var upAxis = BoneIKController._tmpVecs[4];
  80611. var _tmpQuat = BoneIKController._tmpQuat;
  80612. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80613. poleTarget.subtractToRef(bonePos, upAxis);
  80614. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80615. upAxis.y = 1;
  80616. }
  80617. else {
  80618. upAxis.normalize();
  80619. }
  80620. target.subtractToRef(bonePos, yaxis);
  80621. yaxis.normalize();
  80622. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80623. zaxis.normalize();
  80624. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80625. xaxis.normalize();
  80626. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80627. var a = this._bone1Length;
  80628. var b = this._bone2Length;
  80629. var c = BABYLON.Vector3.Distance(bonePos, target);
  80630. if (this._maxReach > 0) {
  80631. c = Math.min(this._maxReach, c);
  80632. }
  80633. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80634. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80635. if (acosa > 1) {
  80636. acosa = 1;
  80637. }
  80638. if (acosb > 1) {
  80639. acosb = 1;
  80640. }
  80641. if (acosa < -1) {
  80642. acosa = -1;
  80643. }
  80644. if (acosb < -1) {
  80645. acosb = -1;
  80646. }
  80647. var angA = Math.acos(acosa);
  80648. var angB = Math.acos(acosb);
  80649. var angC = -angA - angB;
  80650. if (this._rightHandedSystem) {
  80651. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80652. mat2.multiplyToRef(mat1, mat1);
  80653. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80654. mat2.multiplyToRef(mat1, mat1);
  80655. }
  80656. else {
  80657. var _tmpVec = BoneIKController._tmpVecs[5];
  80658. _tmpVec.copyFrom(this._bendAxis);
  80659. _tmpVec.x *= -1;
  80660. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80661. mat2.multiplyToRef(mat1, mat1);
  80662. }
  80663. if (this.poleAngle) {
  80664. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80665. mat1.multiplyToRef(mat2, mat1);
  80666. }
  80667. if (this._bone1) {
  80668. if (this.slerpAmount < 1) {
  80669. if (!this._slerping) {
  80670. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80671. }
  80672. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80673. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80674. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80675. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80676. this._slerping = true;
  80677. }
  80678. else {
  80679. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80680. this._bone1Mat.copyFrom(mat1);
  80681. this._slerping = false;
  80682. }
  80683. }
  80684. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80685. this._bone2Ang = angC;
  80686. };
  80687. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80688. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80689. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80690. return BoneIKController;
  80691. }());
  80692. BABYLON.BoneIKController = BoneIKController;
  80693. })(BABYLON || (BABYLON = {}));
  80694. //# sourceMappingURL=babylon.boneIKController.js.map
  80695. var BABYLON;
  80696. (function (BABYLON) {
  80697. /**
  80698. * Class used to make a bone look toward a point in space
  80699. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80700. */
  80701. var BoneLookController = /** @class */ (function () {
  80702. /**
  80703. * Create a BoneLookController
  80704. * @param mesh the mesh that the bone belongs to
  80705. * @param bone the bone that will be looking to the target
  80706. * @param target the target Vector3 to look at
  80707. * @param settings optional settings:
  80708. * * maxYaw: the maximum angle the bone will yaw to
  80709. * * minYaw: the minimum angle the bone will yaw to
  80710. * * maxPitch: the maximum angle the bone will pitch to
  80711. * * minPitch: the minimum angle the bone will yaw to
  80712. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80713. * * upAxis: the up axis of the coordinate system
  80714. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80715. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80716. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80717. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80718. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80719. * * adjustRoll: used to make an adjustment to the roll of the bone
  80720. **/
  80721. function BoneLookController(mesh, bone, target, options) {
  80722. /**
  80723. * The up axis of the coordinate system that is used when the bone is rotated
  80724. */
  80725. this.upAxis = BABYLON.Vector3.Up();
  80726. /**
  80727. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80728. */
  80729. this.upAxisSpace = BABYLON.Space.LOCAL;
  80730. /**
  80731. * Used to make an adjustment to the yaw of the bone
  80732. */
  80733. this.adjustYaw = 0;
  80734. /**
  80735. * Used to make an adjustment to the pitch of the bone
  80736. */
  80737. this.adjustPitch = 0;
  80738. /**
  80739. * Used to make an adjustment to the roll of the bone
  80740. */
  80741. this.adjustRoll = 0;
  80742. /**
  80743. * 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)
  80744. */
  80745. this.slerpAmount = 1;
  80746. this._boneQuat = BABYLON.Quaternion.Identity();
  80747. this._slerping = false;
  80748. this._firstFrameSkipped = false;
  80749. this._fowardAxis = BABYLON.Vector3.Forward();
  80750. this.mesh = mesh;
  80751. this.bone = bone;
  80752. this.target = target;
  80753. if (options) {
  80754. if (options.adjustYaw) {
  80755. this.adjustYaw = options.adjustYaw;
  80756. }
  80757. if (options.adjustPitch) {
  80758. this.adjustPitch = options.adjustPitch;
  80759. }
  80760. if (options.adjustRoll) {
  80761. this.adjustRoll = options.adjustRoll;
  80762. }
  80763. if (options.maxYaw != null) {
  80764. this.maxYaw = options.maxYaw;
  80765. }
  80766. else {
  80767. this.maxYaw = Math.PI;
  80768. }
  80769. if (options.minYaw != null) {
  80770. this.minYaw = options.minYaw;
  80771. }
  80772. else {
  80773. this.minYaw = -Math.PI;
  80774. }
  80775. if (options.maxPitch != null) {
  80776. this.maxPitch = options.maxPitch;
  80777. }
  80778. else {
  80779. this.maxPitch = Math.PI;
  80780. }
  80781. if (options.minPitch != null) {
  80782. this.minPitch = options.minPitch;
  80783. }
  80784. else {
  80785. this.minPitch = -Math.PI;
  80786. }
  80787. if (options.slerpAmount != null) {
  80788. this.slerpAmount = options.slerpAmount;
  80789. }
  80790. if (options.upAxis != null) {
  80791. this.upAxis = options.upAxis;
  80792. }
  80793. if (options.upAxisSpace != null) {
  80794. this.upAxisSpace = options.upAxisSpace;
  80795. }
  80796. if (options.yawAxis != null || options.pitchAxis != null) {
  80797. var newYawAxis = BABYLON.Axis.Y;
  80798. var newPitchAxis = BABYLON.Axis.X;
  80799. if (options.yawAxis != null) {
  80800. newYawAxis = options.yawAxis.clone();
  80801. newYawAxis.normalize();
  80802. }
  80803. if (options.pitchAxis != null) {
  80804. newPitchAxis = options.pitchAxis.clone();
  80805. newPitchAxis.normalize();
  80806. }
  80807. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80808. this._transformYawPitch = BABYLON.Matrix.Identity();
  80809. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80810. this._transformYawPitchInv = this._transformYawPitch.clone();
  80811. this._transformYawPitch.invert();
  80812. }
  80813. }
  80814. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80815. this.upAxisSpace = BABYLON.Space.LOCAL;
  80816. }
  80817. }
  80818. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80819. /**
  80820. * Gets or sets the minimum yaw angle that the bone can look to
  80821. */
  80822. get: function () {
  80823. return this._minYaw;
  80824. },
  80825. set: function (value) {
  80826. this._minYaw = value;
  80827. this._minYawSin = Math.sin(value);
  80828. this._minYawCos = Math.cos(value);
  80829. if (this._maxYaw != null) {
  80830. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80831. this._yawRange = this._maxYaw - this._minYaw;
  80832. }
  80833. },
  80834. enumerable: true,
  80835. configurable: true
  80836. });
  80837. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80838. /**
  80839. * Gets or sets the maximum yaw angle that the bone can look to
  80840. */
  80841. get: function () {
  80842. return this._maxYaw;
  80843. },
  80844. set: function (value) {
  80845. this._maxYaw = value;
  80846. this._maxYawSin = Math.sin(value);
  80847. this._maxYawCos = Math.cos(value);
  80848. if (this._minYaw != null) {
  80849. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80850. this._yawRange = this._maxYaw - this._minYaw;
  80851. }
  80852. },
  80853. enumerable: true,
  80854. configurable: true
  80855. });
  80856. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80857. /**
  80858. * Gets or sets the minimum pitch angle that the bone can look to
  80859. */
  80860. get: function () {
  80861. return this._minPitch;
  80862. },
  80863. set: function (value) {
  80864. this._minPitch = value;
  80865. this._minPitchTan = Math.tan(value);
  80866. },
  80867. enumerable: true,
  80868. configurable: true
  80869. });
  80870. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80871. /**
  80872. * Gets or sets the maximum pitch angle that the bone can look to
  80873. */
  80874. get: function () {
  80875. return this._maxPitch;
  80876. },
  80877. set: function (value) {
  80878. this._maxPitch = value;
  80879. this._maxPitchTan = Math.tan(value);
  80880. },
  80881. enumerable: true,
  80882. configurable: true
  80883. });
  80884. /**
  80885. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80886. */
  80887. BoneLookController.prototype.update = function () {
  80888. //skip the first frame when slerping so that the mesh rotation is correct
  80889. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80890. this._firstFrameSkipped = true;
  80891. return;
  80892. }
  80893. var bone = this.bone;
  80894. var bonePos = BoneLookController._tmpVecs[0];
  80895. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80896. var target = this.target;
  80897. var _tmpMat1 = BoneLookController._tmpMats[0];
  80898. var _tmpMat2 = BoneLookController._tmpMats[1];
  80899. var mesh = this.mesh;
  80900. var parentBone = bone.getParent();
  80901. var upAxis = BoneLookController._tmpVecs[1];
  80902. upAxis.copyFrom(this.upAxis);
  80903. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80904. if (this._transformYawPitch) {
  80905. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80906. }
  80907. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80908. }
  80909. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80910. mesh.getDirectionToRef(upAxis, upAxis);
  80911. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80912. upAxis.normalize();
  80913. }
  80914. }
  80915. var checkYaw = false;
  80916. var checkPitch = false;
  80917. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80918. checkYaw = true;
  80919. }
  80920. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80921. checkPitch = true;
  80922. }
  80923. if (checkYaw || checkPitch) {
  80924. var spaceMat = BoneLookController._tmpMats[2];
  80925. var spaceMatInv = BoneLookController._tmpMats[3];
  80926. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80927. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80928. }
  80929. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80930. spaceMat.copyFrom(mesh.getWorldMatrix());
  80931. }
  80932. else {
  80933. var forwardAxis = BoneLookController._tmpVecs[2];
  80934. forwardAxis.copyFrom(this._fowardAxis);
  80935. if (this._transformYawPitch) {
  80936. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80937. }
  80938. if (parentBone) {
  80939. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80940. }
  80941. else {
  80942. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80943. }
  80944. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80945. rightAxis.normalize();
  80946. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80947. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80948. }
  80949. spaceMat.invertToRef(spaceMatInv);
  80950. var xzlen = null;
  80951. if (checkPitch) {
  80952. var localTarget = BoneLookController._tmpVecs[3];
  80953. target.subtractToRef(bonePos, localTarget);
  80954. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80955. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80956. var pitch = Math.atan2(localTarget.y, xzlen);
  80957. var newPitch = pitch;
  80958. if (pitch > this._maxPitch) {
  80959. localTarget.y = this._maxPitchTan * xzlen;
  80960. newPitch = this._maxPitch;
  80961. }
  80962. else if (pitch < this._minPitch) {
  80963. localTarget.y = this._minPitchTan * xzlen;
  80964. newPitch = this._minPitch;
  80965. }
  80966. if (pitch != newPitch) {
  80967. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80968. localTarget.addInPlace(bonePos);
  80969. target = localTarget;
  80970. }
  80971. }
  80972. if (checkYaw) {
  80973. var localTarget = BoneLookController._tmpVecs[4];
  80974. target.subtractToRef(bonePos, localTarget);
  80975. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80976. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80977. var newYaw = yaw;
  80978. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80979. if (xzlen == null) {
  80980. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80981. }
  80982. if (this._yawRange > Math.PI) {
  80983. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80984. localTarget.z = this._maxYawCos * xzlen;
  80985. localTarget.x = this._maxYawSin * xzlen;
  80986. newYaw = this._maxYaw;
  80987. }
  80988. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80989. localTarget.z = this._minYawCos * xzlen;
  80990. localTarget.x = this._minYawSin * xzlen;
  80991. newYaw = this._minYaw;
  80992. }
  80993. }
  80994. else {
  80995. if (yaw > this._maxYaw) {
  80996. localTarget.z = this._maxYawCos * xzlen;
  80997. localTarget.x = this._maxYawSin * xzlen;
  80998. newYaw = this._maxYaw;
  80999. }
  81000. else if (yaw < this._minYaw) {
  81001. localTarget.z = this._minYawCos * xzlen;
  81002. localTarget.x = this._minYawSin * xzlen;
  81003. newYaw = this._minYaw;
  81004. }
  81005. }
  81006. }
  81007. if (this._slerping && this._yawRange > Math.PI) {
  81008. //are we going to be crossing into the min/max region?
  81009. var boneFwd = BoneLookController._tmpVecs[8];
  81010. boneFwd.copyFrom(BABYLON.Axis.Z);
  81011. if (this._transformYawPitch) {
  81012. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81013. }
  81014. var boneRotMat = BoneLookController._tmpMats[4];
  81015. this._boneQuat.toRotationMatrix(boneRotMat);
  81016. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81017. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81018. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81019. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81020. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81021. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81022. if (angBtwTar > angBtwMidYaw) {
  81023. if (xzlen == null) {
  81024. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81025. }
  81026. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81027. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81028. if (angBtwMin < angBtwMax) {
  81029. newYaw = boneYaw + Math.PI * .75;
  81030. localTarget.z = Math.cos(newYaw) * xzlen;
  81031. localTarget.x = Math.sin(newYaw) * xzlen;
  81032. }
  81033. else {
  81034. newYaw = boneYaw - Math.PI * .75;
  81035. localTarget.z = Math.cos(newYaw) * xzlen;
  81036. localTarget.x = Math.sin(newYaw) * xzlen;
  81037. }
  81038. }
  81039. }
  81040. if (yaw != newYaw) {
  81041. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81042. localTarget.addInPlace(bonePos);
  81043. target = localTarget;
  81044. }
  81045. }
  81046. }
  81047. var zaxis = BoneLookController._tmpVecs[5];
  81048. var xaxis = BoneLookController._tmpVecs[6];
  81049. var yaxis = BoneLookController._tmpVecs[7];
  81050. var _tmpQuat = BoneLookController._tmpQuat;
  81051. target.subtractToRef(bonePos, zaxis);
  81052. zaxis.normalize();
  81053. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81054. xaxis.normalize();
  81055. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81056. yaxis.normalize();
  81057. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81058. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81059. return;
  81060. }
  81061. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81062. return;
  81063. }
  81064. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81065. return;
  81066. }
  81067. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81068. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81069. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81070. }
  81071. if (this.slerpAmount < 1) {
  81072. if (!this._slerping) {
  81073. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81074. }
  81075. if (this._transformYawPitch) {
  81076. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81077. }
  81078. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81079. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81080. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81081. this._slerping = true;
  81082. }
  81083. else {
  81084. if (this._transformYawPitch) {
  81085. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81086. }
  81087. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81088. this._slerping = false;
  81089. }
  81090. };
  81091. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81092. var angDiff = ang2 - ang1;
  81093. angDiff %= Math.PI * 2;
  81094. if (angDiff > Math.PI) {
  81095. angDiff -= Math.PI * 2;
  81096. }
  81097. else if (angDiff < -Math.PI) {
  81098. angDiff += Math.PI * 2;
  81099. }
  81100. return angDiff;
  81101. };
  81102. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81103. ang1 %= (2 * Math.PI);
  81104. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81105. ang2 %= (2 * Math.PI);
  81106. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81107. var ab = 0;
  81108. if (ang1 < ang2) {
  81109. ab = ang2 - ang1;
  81110. }
  81111. else {
  81112. ab = ang1 - ang2;
  81113. }
  81114. if (ab > Math.PI) {
  81115. ab = Math.PI * 2 - ab;
  81116. }
  81117. return ab;
  81118. };
  81119. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81120. ang %= (2 * Math.PI);
  81121. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81122. ang1 %= (2 * Math.PI);
  81123. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81124. ang2 %= (2 * Math.PI);
  81125. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81126. if (ang1 < ang2) {
  81127. if (ang > ang1 && ang < ang2) {
  81128. return true;
  81129. }
  81130. }
  81131. else {
  81132. if (ang > ang2 && ang < ang1) {
  81133. return true;
  81134. }
  81135. }
  81136. return false;
  81137. };
  81138. 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()];
  81139. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81140. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81141. return BoneLookController;
  81142. }());
  81143. BABYLON.BoneLookController = BoneLookController;
  81144. })(BABYLON || (BABYLON = {}));
  81145. //# sourceMappingURL=babylon.boneLookController.js.map
  81146. var BABYLON;
  81147. (function (BABYLON) {
  81148. /**
  81149. * Class used to handle skinning animations
  81150. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81151. */
  81152. var Skeleton = /** @class */ (function () {
  81153. /**
  81154. * Creates a new skeleton
  81155. * @param name defines the skeleton name
  81156. * @param id defines the skeleton Id
  81157. * @param scene defines the hosting scene
  81158. */
  81159. function Skeleton(
  81160. /** defines the skeleton name */
  81161. name,
  81162. /** defines the skeleton Id */
  81163. id, scene) {
  81164. this.name = name;
  81165. this.id = id;
  81166. /**
  81167. * Gets the list of child bones
  81168. */
  81169. this.bones = new Array();
  81170. /**
  81171. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81172. */
  81173. this.needInitialSkinMatrix = false;
  81174. this._isDirty = true;
  81175. this._meshesWithPoseMatrix = new Array();
  81176. this._identity = BABYLON.Matrix.Identity();
  81177. this._ranges = {};
  81178. this._lastAbsoluteTransformsUpdateId = -1;
  81179. /**
  81180. * Specifies if the skeleton should be serialized
  81181. */
  81182. this.doNotSerialize = false;
  81183. this._animationPropertiesOverride = null;
  81184. // Events
  81185. /**
  81186. * An observable triggered before computing the skeleton's matrices
  81187. */
  81188. this.onBeforeComputeObservable = new BABYLON.Observable();
  81189. this.bones = [];
  81190. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81191. scene.skeletons.push(this);
  81192. //make sure it will recalculate the matrix next time prepare is called.
  81193. this._isDirty = true;
  81194. }
  81195. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81196. /**
  81197. * Gets or sets the animation properties override
  81198. */
  81199. get: function () {
  81200. if (!this._animationPropertiesOverride) {
  81201. return this._scene.animationPropertiesOverride;
  81202. }
  81203. return this._animationPropertiesOverride;
  81204. },
  81205. set: function (value) {
  81206. this._animationPropertiesOverride = value;
  81207. },
  81208. enumerable: true,
  81209. configurable: true
  81210. });
  81211. // Members
  81212. /**
  81213. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81214. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81215. * @returns a Float32Array containing matrices data
  81216. */
  81217. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81218. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81219. return mesh._bonesTransformMatrices;
  81220. }
  81221. if (!this._transformMatrices) {
  81222. this.prepare();
  81223. }
  81224. return this._transformMatrices;
  81225. };
  81226. /**
  81227. * Gets the current hosting scene
  81228. * @returns a scene object
  81229. */
  81230. Skeleton.prototype.getScene = function () {
  81231. return this._scene;
  81232. };
  81233. // Methods
  81234. /**
  81235. * Gets a string representing the current skeleton data
  81236. * @param fullDetails defines a boolean indicating if we want a verbose version
  81237. * @returns a string representing the current skeleton data
  81238. */
  81239. Skeleton.prototype.toString = function (fullDetails) {
  81240. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81241. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81242. if (fullDetails) {
  81243. ret += ", Ranges: {";
  81244. var first = true;
  81245. for (var name_1 in this._ranges) {
  81246. if (first) {
  81247. ret += ", ";
  81248. first = false;
  81249. }
  81250. ret += name_1;
  81251. }
  81252. ret += "}";
  81253. }
  81254. return ret;
  81255. };
  81256. /**
  81257. * Get bone's index searching by name
  81258. * @param name defines bone's name to search for
  81259. * @return the indice of the bone. Returns -1 if not found
  81260. */
  81261. Skeleton.prototype.getBoneIndexByName = function (name) {
  81262. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81263. if (this.bones[boneIndex].name === name) {
  81264. return boneIndex;
  81265. }
  81266. }
  81267. return -1;
  81268. };
  81269. /**
  81270. * Creater a new animation range
  81271. * @param name defines the name of the range
  81272. * @param from defines the start key
  81273. * @param to defines the end key
  81274. */
  81275. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81276. // check name not already in use
  81277. if (!this._ranges[name]) {
  81278. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81279. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81280. if (this.bones[i].animations[0]) {
  81281. this.bones[i].animations[0].createRange(name, from, to);
  81282. }
  81283. }
  81284. }
  81285. };
  81286. /**
  81287. * Delete a specific animation range
  81288. * @param name defines the name of the range
  81289. * @param deleteFrames defines if frames must be removed as well
  81290. */
  81291. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81292. if (deleteFrames === void 0) { deleteFrames = true; }
  81293. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81294. if (this.bones[i].animations[0]) {
  81295. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81296. }
  81297. }
  81298. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81299. };
  81300. /**
  81301. * Gets a specific animation range
  81302. * @param name defines the name of the range to look for
  81303. * @returns the requested animation range or null if not found
  81304. */
  81305. Skeleton.prototype.getAnimationRange = function (name) {
  81306. return this._ranges[name];
  81307. };
  81308. /**
  81309. * Gets the list of all animation ranges defined on this skeleton
  81310. * @returns an array
  81311. */
  81312. Skeleton.prototype.getAnimationRanges = function () {
  81313. var animationRanges = [];
  81314. var name;
  81315. var i = 0;
  81316. for (name in this._ranges) {
  81317. animationRanges[i] = this._ranges[name];
  81318. i++;
  81319. }
  81320. return animationRanges;
  81321. };
  81322. /**
  81323. * Copy animation range from a source skeleton.
  81324. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81325. * @param source defines the source skeleton
  81326. * @param name defines the name of the range to copy
  81327. * @param rescaleAsRequired defines if rescaling must be applied if required
  81328. * @returns true if operation was successful
  81329. */
  81330. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81331. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81332. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81333. return false;
  81334. }
  81335. var ret = true;
  81336. var frameOffset = this._getHighestAnimationFrame() + 1;
  81337. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81338. var boneDict = {};
  81339. var sourceBones = source.bones;
  81340. var nBones;
  81341. var i;
  81342. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81343. boneDict[sourceBones[i].name] = sourceBones[i];
  81344. }
  81345. if (this.bones.length !== sourceBones.length) {
  81346. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81347. ret = false;
  81348. }
  81349. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81350. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81351. var boneName = this.bones[i].name;
  81352. var sourceBone = boneDict[boneName];
  81353. if (sourceBone) {
  81354. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81355. }
  81356. else {
  81357. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81358. ret = false;
  81359. }
  81360. }
  81361. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81362. var range = source.getAnimationRange(name);
  81363. if (range) {
  81364. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81365. }
  81366. return ret;
  81367. };
  81368. /**
  81369. * Forces the skeleton to go to rest pose
  81370. */
  81371. Skeleton.prototype.returnToRest = function () {
  81372. for (var index = 0; index < this.bones.length; index++) {
  81373. this.bones[index].returnToRest();
  81374. }
  81375. };
  81376. Skeleton.prototype._getHighestAnimationFrame = function () {
  81377. var ret = 0;
  81378. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81379. if (this.bones[i].animations[0]) {
  81380. var highest = this.bones[i].animations[0].getHighestFrame();
  81381. if (ret < highest) {
  81382. ret = highest;
  81383. }
  81384. }
  81385. }
  81386. return ret;
  81387. };
  81388. /**
  81389. * Begin a specific animation range
  81390. * @param name defines the name of the range to start
  81391. * @param loop defines if looping must be turned on (false by default)
  81392. * @param speedRatio defines the speed ratio to apply (1 by default)
  81393. * @param onAnimationEnd defines a callback which will be called when animation will end
  81394. * @returns a new animatable
  81395. */
  81396. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81397. var range = this.getAnimationRange(name);
  81398. if (!range) {
  81399. return null;
  81400. }
  81401. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81402. };
  81403. /** @hidden */
  81404. Skeleton.prototype._markAsDirty = function () {
  81405. this._isDirty = true;
  81406. };
  81407. /** @hidden */
  81408. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81409. this._meshesWithPoseMatrix.push(mesh);
  81410. };
  81411. /** @hidden */
  81412. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81413. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81414. if (index > -1) {
  81415. this._meshesWithPoseMatrix.splice(index, 1);
  81416. }
  81417. };
  81418. /** @hidden */
  81419. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81420. this.onBeforeComputeObservable.notifyObservers(this);
  81421. for (var index = 0; index < this.bones.length; index++) {
  81422. var bone = this.bones[index];
  81423. var parentBone = bone.getParent();
  81424. if (parentBone) {
  81425. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81426. }
  81427. else {
  81428. if (initialSkinMatrix) {
  81429. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81430. }
  81431. else {
  81432. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81433. }
  81434. }
  81435. if (bone._index !== -1) {
  81436. var mappedIndex = bone._index === null ? index : bone._index;
  81437. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81438. }
  81439. }
  81440. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81441. };
  81442. /**
  81443. * Build all resources required to render a skeleton
  81444. */
  81445. Skeleton.prototype.prepare = function () {
  81446. if (!this._isDirty) {
  81447. return;
  81448. }
  81449. if (this.needInitialSkinMatrix) {
  81450. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81451. var mesh = this._meshesWithPoseMatrix[index];
  81452. var poseMatrix = mesh.getPoseMatrix();
  81453. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81454. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81455. }
  81456. if (this._synchronizedWithMesh !== mesh) {
  81457. this._synchronizedWithMesh = mesh;
  81458. // Prepare bones
  81459. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81460. var bone = this.bones[boneIndex];
  81461. if (!bone.getParent()) {
  81462. var matrix = bone.getBaseMatrix();
  81463. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81464. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81465. }
  81466. }
  81467. }
  81468. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81469. }
  81470. }
  81471. else {
  81472. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81473. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81474. }
  81475. this._computeTransformMatrices(this._transformMatrices, null);
  81476. }
  81477. this._isDirty = false;
  81478. this._scene._activeBones.addCount(this.bones.length, false);
  81479. };
  81480. /**
  81481. * Gets the list of animatables currently running for this skeleton
  81482. * @returns an array of animatables
  81483. */
  81484. Skeleton.prototype.getAnimatables = function () {
  81485. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81486. this._animatables = [];
  81487. for (var index = 0; index < this.bones.length; index++) {
  81488. this._animatables.push(this.bones[index]);
  81489. }
  81490. }
  81491. return this._animatables;
  81492. };
  81493. /**
  81494. * Clone the current skeleton
  81495. * @param name defines the name of the new skeleton
  81496. * @param id defines the id of the enw skeleton
  81497. * @returns the new skeleton
  81498. */
  81499. Skeleton.prototype.clone = function (name, id) {
  81500. var result = new Skeleton(name, id || name, this._scene);
  81501. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81502. for (var index = 0; index < this.bones.length; index++) {
  81503. var source = this.bones[index];
  81504. var parentBone = null;
  81505. var parent_1 = source.getParent();
  81506. if (parent_1) {
  81507. var parentIndex = this.bones.indexOf(parent_1);
  81508. parentBone = result.bones[parentIndex];
  81509. }
  81510. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81511. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81512. }
  81513. if (this._ranges) {
  81514. result._ranges = {};
  81515. for (var rangeName in this._ranges) {
  81516. var range = this._ranges[rangeName];
  81517. if (range) {
  81518. result._ranges[rangeName] = range.clone();
  81519. }
  81520. }
  81521. }
  81522. this._isDirty = true;
  81523. return result;
  81524. };
  81525. /**
  81526. * Enable animation blending for this skeleton
  81527. * @param blendingSpeed defines the blending speed to apply
  81528. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81529. */
  81530. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81531. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81532. this.bones.forEach(function (bone) {
  81533. bone.animations.forEach(function (animation) {
  81534. animation.enableBlending = true;
  81535. animation.blendingSpeed = blendingSpeed;
  81536. });
  81537. });
  81538. };
  81539. /**
  81540. * Releases all resources associated with the current skeleton
  81541. */
  81542. Skeleton.prototype.dispose = function () {
  81543. this._meshesWithPoseMatrix = [];
  81544. // Animations
  81545. this.getScene().stopAnimation(this);
  81546. // Remove from scene
  81547. this.getScene().removeSkeleton(this);
  81548. };
  81549. /**
  81550. * Serialize the skeleton in a JSON object
  81551. * @returns a JSON object
  81552. */
  81553. Skeleton.prototype.serialize = function () {
  81554. var serializationObject = {};
  81555. serializationObject.name = this.name;
  81556. serializationObject.id = this.id;
  81557. if (this.dimensionsAtRest) {
  81558. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81559. }
  81560. serializationObject.bones = [];
  81561. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81562. for (var index = 0; index < this.bones.length; index++) {
  81563. var bone = this.bones[index];
  81564. var parent_2 = bone.getParent();
  81565. var serializedBone = {
  81566. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81567. name: bone.name,
  81568. matrix: bone.getBaseMatrix().toArray(),
  81569. rest: bone.getRestPose().toArray()
  81570. };
  81571. serializationObject.bones.push(serializedBone);
  81572. if (bone.length) {
  81573. serializedBone.length = bone.length;
  81574. }
  81575. if (bone.metadata) {
  81576. serializedBone.metadata = bone.metadata;
  81577. }
  81578. if (bone.animations && bone.animations.length > 0) {
  81579. serializedBone.animation = bone.animations[0].serialize();
  81580. }
  81581. serializationObject.ranges = [];
  81582. for (var name in this._ranges) {
  81583. var source = this._ranges[name];
  81584. if (!source) {
  81585. continue;
  81586. }
  81587. var range = {};
  81588. range.name = name;
  81589. range.from = source.from;
  81590. range.to = source.to;
  81591. serializationObject.ranges.push(range);
  81592. }
  81593. }
  81594. return serializationObject;
  81595. };
  81596. /**
  81597. * Creates a new skeleton from serialized data
  81598. * @param parsedSkeleton defines the serialized data
  81599. * @param scene defines the hosting scene
  81600. * @returns a new skeleton
  81601. */
  81602. Skeleton.Parse = function (parsedSkeleton, scene) {
  81603. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81604. if (parsedSkeleton.dimensionsAtRest) {
  81605. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81606. }
  81607. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81608. var index;
  81609. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81610. var parsedBone = parsedSkeleton.bones[index];
  81611. var parentBone = null;
  81612. if (parsedBone.parentBoneIndex > -1) {
  81613. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81614. }
  81615. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81616. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81617. if (parsedBone.length) {
  81618. bone.length = parsedBone.length;
  81619. }
  81620. if (parsedBone.metadata) {
  81621. bone.metadata = parsedBone.metadata;
  81622. }
  81623. if (parsedBone.animation) {
  81624. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81625. }
  81626. }
  81627. // placed after bones, so createAnimationRange can cascade down
  81628. if (parsedSkeleton.ranges) {
  81629. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81630. var data = parsedSkeleton.ranges[index];
  81631. skeleton.createAnimationRange(data.name, data.from, data.to);
  81632. }
  81633. }
  81634. return skeleton;
  81635. };
  81636. /**
  81637. * Compute all node absolute transforms
  81638. * @param forceUpdate defines if computation must be done even if cache is up to date
  81639. */
  81640. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81641. if (forceUpdate === void 0) { forceUpdate = false; }
  81642. var renderId = this._scene.getRenderId();
  81643. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81644. this.bones[0].computeAbsoluteTransforms();
  81645. this._lastAbsoluteTransformsUpdateId = renderId;
  81646. }
  81647. };
  81648. /**
  81649. * Gets the root pose matrix
  81650. * @returns a matrix
  81651. */
  81652. Skeleton.prototype.getPoseMatrix = function () {
  81653. var poseMatrix = null;
  81654. if (this._meshesWithPoseMatrix.length > 0) {
  81655. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81656. }
  81657. return poseMatrix;
  81658. };
  81659. /**
  81660. * Sorts bones per internal index
  81661. */
  81662. Skeleton.prototype.sortBones = function () {
  81663. var bones = new Array();
  81664. var visited = new Array(this.bones.length);
  81665. for (var index = 0; index < this.bones.length; index++) {
  81666. this._sortBones(index, bones, visited);
  81667. }
  81668. this.bones = bones;
  81669. };
  81670. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81671. if (visited[index]) {
  81672. return;
  81673. }
  81674. visited[index] = true;
  81675. var bone = this.bones[index];
  81676. if (bone._index === undefined) {
  81677. bone._index = index;
  81678. }
  81679. var parentBone = bone.getParent();
  81680. if (parentBone) {
  81681. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81682. }
  81683. bones.push(bone);
  81684. };
  81685. return Skeleton;
  81686. }());
  81687. BABYLON.Skeleton = Skeleton;
  81688. })(BABYLON || (BABYLON = {}));
  81689. //# sourceMappingURL=babylon.skeleton.js.map
  81690. var BABYLON;
  81691. (function (BABYLON) {
  81692. /**
  81693. * Class representing spherical polynomial coefficients to the 3rd degree
  81694. */
  81695. var SphericalPolynomial = /** @class */ (function () {
  81696. function SphericalPolynomial() {
  81697. /**
  81698. * The x coefficients of the spherical polynomial
  81699. */
  81700. this.x = BABYLON.Vector3.Zero();
  81701. /**
  81702. * The y coefficients of the spherical polynomial
  81703. */
  81704. this.y = BABYLON.Vector3.Zero();
  81705. /**
  81706. * The z coefficients of the spherical polynomial
  81707. */
  81708. this.z = BABYLON.Vector3.Zero();
  81709. /**
  81710. * The xx coefficients of the spherical polynomial
  81711. */
  81712. this.xx = BABYLON.Vector3.Zero();
  81713. /**
  81714. * The yy coefficients of the spherical polynomial
  81715. */
  81716. this.yy = BABYLON.Vector3.Zero();
  81717. /**
  81718. * The zz coefficients of the spherical polynomial
  81719. */
  81720. this.zz = BABYLON.Vector3.Zero();
  81721. /**
  81722. * The xy coefficients of the spherical polynomial
  81723. */
  81724. this.xy = BABYLON.Vector3.Zero();
  81725. /**
  81726. * The yz coefficients of the spherical polynomial
  81727. */
  81728. this.yz = BABYLON.Vector3.Zero();
  81729. /**
  81730. * The zx coefficients of the spherical polynomial
  81731. */
  81732. this.zx = BABYLON.Vector3.Zero();
  81733. }
  81734. /**
  81735. * Adds an ambient color to the spherical polynomial
  81736. * @param color the color to add
  81737. */
  81738. SphericalPolynomial.prototype.addAmbient = function (color) {
  81739. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81740. this.xx = this.xx.add(colorVector);
  81741. this.yy = this.yy.add(colorVector);
  81742. this.zz = this.zz.add(colorVector);
  81743. };
  81744. /**
  81745. * Scales the spherical polynomial by the given amount
  81746. * @param scale the amount to scale
  81747. */
  81748. SphericalPolynomial.prototype.scale = function (scale) {
  81749. this.x = this.x.scale(scale);
  81750. this.y = this.y.scale(scale);
  81751. this.z = this.z.scale(scale);
  81752. this.xx = this.xx.scale(scale);
  81753. this.yy = this.yy.scale(scale);
  81754. this.zz = this.zz.scale(scale);
  81755. this.yz = this.yz.scale(scale);
  81756. this.zx = this.zx.scale(scale);
  81757. this.xy = this.xy.scale(scale);
  81758. };
  81759. /**
  81760. * Gets the spherical polynomial from harmonics
  81761. * @param harmonics the spherical harmonics
  81762. * @returns the spherical polynomial
  81763. */
  81764. SphericalPolynomial.FromHarmonics = function (harmonics) {
  81765. var result = new SphericalPolynomial();
  81766. result.x = harmonics.l11.scale(1.02333);
  81767. result.y = harmonics.l1_1.scale(1.02333);
  81768. result.z = harmonics.l10.scale(1.02333);
  81769. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  81770. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  81771. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  81772. result.yz = harmonics.l2_1.scale(0.858086);
  81773. result.zx = harmonics.l21.scale(0.858086);
  81774. result.xy = harmonics.l2_2.scale(0.858086);
  81775. result.scale(1.0 / Math.PI);
  81776. return result;
  81777. };
  81778. /**
  81779. * Constructs a spherical polynomial from an array.
  81780. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  81781. * @returns the spherical polynomial
  81782. */
  81783. SphericalPolynomial.FromArray = function (data) {
  81784. var sp = new SphericalPolynomial();
  81785. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  81786. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  81787. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  81788. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  81789. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  81790. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  81791. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  81792. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  81793. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  81794. return sp;
  81795. };
  81796. return SphericalPolynomial;
  81797. }());
  81798. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81799. /**
  81800. * Class representing spherical harmonics coefficients to the 3rd degree
  81801. */
  81802. var SphericalHarmonics = /** @class */ (function () {
  81803. function SphericalHarmonics() {
  81804. /**
  81805. * The l0,0 coefficients of the spherical harmonics
  81806. */
  81807. this.l00 = BABYLON.Vector3.Zero();
  81808. /**
  81809. * The l1,-1 coefficients of the spherical harmonics
  81810. */
  81811. this.l1_1 = BABYLON.Vector3.Zero();
  81812. /**
  81813. * The l1,0 coefficients of the spherical harmonics
  81814. */
  81815. this.l10 = BABYLON.Vector3.Zero();
  81816. /**
  81817. * The l1,1 coefficients of the spherical harmonics
  81818. */
  81819. this.l11 = BABYLON.Vector3.Zero();
  81820. /**
  81821. * The l2,-2 coefficients of the spherical harmonics
  81822. */
  81823. this.l2_2 = BABYLON.Vector3.Zero();
  81824. /**
  81825. * The l2,-1 coefficients of the spherical harmonics
  81826. */
  81827. this.l2_1 = BABYLON.Vector3.Zero();
  81828. /**
  81829. * The l2,0 coefficients of the spherical harmonics
  81830. */
  81831. this.l20 = BABYLON.Vector3.Zero();
  81832. /**
  81833. * The l2,1 coefficients of the spherical harmonics
  81834. */
  81835. this.l21 = BABYLON.Vector3.Zero();
  81836. /**
  81837. * The l2,2 coefficients of the spherical harmonics
  81838. */
  81839. this.lL22 = BABYLON.Vector3.Zero();
  81840. }
  81841. /**
  81842. * Adds a light to the spherical harmonics
  81843. * @param direction the direction of the light
  81844. * @param color the color of the light
  81845. * @param deltaSolidAngle the delta solid angle of the light
  81846. */
  81847. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81848. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81849. var c = colorVector.scale(deltaSolidAngle);
  81850. this.l00 = this.l00.add(c.scale(0.282095));
  81851. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  81852. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  81853. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  81854. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81855. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81856. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  81857. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81858. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81859. };
  81860. /**
  81861. * Scales the spherical harmonics by the given amount
  81862. * @param scale the amount to scale
  81863. */
  81864. SphericalHarmonics.prototype.scale = function (scale) {
  81865. this.l00 = this.l00.scale(scale);
  81866. this.l1_1 = this.l1_1.scale(scale);
  81867. this.l10 = this.l10.scale(scale);
  81868. this.l11 = this.l11.scale(scale);
  81869. this.l2_2 = this.l2_2.scale(scale);
  81870. this.l2_1 = this.l2_1.scale(scale);
  81871. this.l20 = this.l20.scale(scale);
  81872. this.l21 = this.l21.scale(scale);
  81873. this.lL22 = this.lL22.scale(scale);
  81874. };
  81875. /**
  81876. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81877. *
  81878. * ```
  81879. * E_lm = A_l * L_lm
  81880. * ```
  81881. *
  81882. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81883. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81884. * the scaling factors are given in equation 9.
  81885. */
  81886. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81887. // Constant (Band 0)
  81888. this.l00 = this.l00.scale(3.141593);
  81889. // Linear (Band 1)
  81890. this.l1_1 = this.l1_1.scale(2.094395);
  81891. this.l10 = this.l10.scale(2.094395);
  81892. this.l11 = this.l11.scale(2.094395);
  81893. // Quadratic (Band 2)
  81894. this.l2_2 = this.l2_2.scale(0.785398);
  81895. this.l2_1 = this.l2_1.scale(0.785398);
  81896. this.l20 = this.l20.scale(0.785398);
  81897. this.l21 = this.l21.scale(0.785398);
  81898. this.lL22 = this.lL22.scale(0.785398);
  81899. };
  81900. /**
  81901. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81902. *
  81903. * ```
  81904. * L = (1/pi) * E * rho
  81905. * ```
  81906. *
  81907. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81908. */
  81909. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81910. this.scale(1.0 / Math.PI);
  81911. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81912. // (The pixel shader must apply albedo after texture fetches, etc).
  81913. };
  81914. /**
  81915. * Gets the spherical harmonics from polynomial
  81916. * @param polynomial the spherical polynomial
  81917. * @returns the spherical harmonics
  81918. */
  81919. SphericalHarmonics.FromPolynomial = function (polynomial) {
  81920. var result = new SphericalHarmonics();
  81921. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81922. result.l1_1 = polynomial.y.scale(0.977204);
  81923. result.l10 = polynomial.z.scale(0.977204);
  81924. result.l11 = polynomial.x.scale(0.977204);
  81925. result.l2_2 = polynomial.xy.scale(1.16538);
  81926. result.l2_1 = polynomial.yz.scale(1.16538);
  81927. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81928. result.l21 = polynomial.zx.scale(1.16538);
  81929. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81930. result.scale(Math.PI);
  81931. return result;
  81932. };
  81933. /**
  81934. * Constructs a spherical harmonics from an array.
  81935. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  81936. * @returns the spherical harmonics
  81937. */
  81938. SphericalHarmonics.FromArray = function (data) {
  81939. var sh = new SphericalHarmonics();
  81940. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  81941. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  81942. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  81943. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  81944. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  81945. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  81946. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  81947. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  81948. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  81949. return sh;
  81950. };
  81951. return SphericalHarmonics;
  81952. }());
  81953. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81954. })(BABYLON || (BABYLON = {}));
  81955. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81956. var BABYLON;
  81957. (function (BABYLON) {
  81958. var FileFaceOrientation = /** @class */ (function () {
  81959. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81960. this.name = name;
  81961. this.worldAxisForNormal = worldAxisForNormal;
  81962. this.worldAxisForFileX = worldAxisForFileX;
  81963. this.worldAxisForFileY = worldAxisForFileY;
  81964. }
  81965. return FileFaceOrientation;
  81966. }());
  81967. ;
  81968. /**
  81969. * Helper class dealing with the extraction of spherical polynomial dataArray
  81970. * from a cube map.
  81971. */
  81972. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81973. function CubeMapToSphericalPolynomialTools() {
  81974. }
  81975. /**
  81976. * Converts a texture to the according Spherical Polynomial data.
  81977. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81978. *
  81979. * @param texture The texture to extract the information from.
  81980. * @return The Spherical Polynomial data.
  81981. */
  81982. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81983. if (!texture.isCube) {
  81984. // Only supports cube Textures currently.
  81985. return null;
  81986. }
  81987. var size = texture.getSize().width;
  81988. var right = texture.readPixels(0);
  81989. var left = texture.readPixels(1);
  81990. var up;
  81991. var down;
  81992. if (texture.isRenderTarget) {
  81993. up = texture.readPixels(3);
  81994. down = texture.readPixels(2);
  81995. }
  81996. else {
  81997. up = texture.readPixels(2);
  81998. down = texture.readPixels(3);
  81999. }
  82000. var front = texture.readPixels(4);
  82001. var back = texture.readPixels(5);
  82002. var gammaSpace = texture.gammaSpace;
  82003. // Always read as RGBA.
  82004. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82005. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82006. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82007. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82008. }
  82009. var cubeInfo = {
  82010. size: size,
  82011. right: right,
  82012. left: left,
  82013. up: up,
  82014. down: down,
  82015. front: front,
  82016. back: back,
  82017. format: format,
  82018. type: type,
  82019. gammaSpace: gammaSpace,
  82020. };
  82021. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82022. };
  82023. /**
  82024. * Converts a cubemap to the according Spherical Polynomial data.
  82025. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82026. *
  82027. * @param cubeInfo The Cube map to extract the information from.
  82028. * @return The Spherical Polynomial data.
  82029. */
  82030. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82031. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82032. var totalSolidAngle = 0.0;
  82033. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82034. var du = 2.0 / cubeInfo.size;
  82035. var dv = du;
  82036. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82037. var minUV = du * 0.5 - 1.0;
  82038. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82039. var fileFace = this.FileFaces[faceIndex];
  82040. var dataArray = cubeInfo[fileFace.name];
  82041. var v = minUV;
  82042. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82043. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82044. // Because SP is still linear, so summation is fine in that basis.
  82045. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82046. for (var y = 0; y < cubeInfo.size; y++) {
  82047. var u = minUV;
  82048. for (var x = 0; x < cubeInfo.size; x++) {
  82049. // World direction (not normalised)
  82050. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82051. worldDirection.normalize();
  82052. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82053. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82054. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82055. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82056. // Handle Integer types.
  82057. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82058. r /= 255;
  82059. g /= 255;
  82060. b /= 255;
  82061. }
  82062. // Handle Gamma space textures.
  82063. if (cubeInfo.gammaSpace) {
  82064. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82065. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82066. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82067. }
  82068. var color = new BABYLON.Color3(r, g, b);
  82069. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82070. totalSolidAngle += deltaSolidAngle;
  82071. u += du;
  82072. }
  82073. v += dv;
  82074. }
  82075. }
  82076. // Solid angle for entire sphere is 4*pi
  82077. var sphereSolidAngle = 4.0 * Math.PI;
  82078. // Adjust the solid angle to allow for how many faces we processed.
  82079. var facesProcessed = 6.0;
  82080. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82081. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82082. // This is needed because the numerical integration over the cube uses a
  82083. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82084. // and also to compensate for accumulative error due to float precision in the summation.
  82085. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82086. sphericalHarmonics.scale(correctionFactor);
  82087. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82088. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82089. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82090. };
  82091. CubeMapToSphericalPolynomialTools.FileFaces = [
  82092. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82093. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82094. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82095. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82096. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82097. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82098. ];
  82099. return CubeMapToSphericalPolynomialTools;
  82100. }());
  82101. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82102. })(BABYLON || (BABYLON = {}));
  82103. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82104. var BABYLON;
  82105. (function (BABYLON) {
  82106. /**
  82107. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82108. */
  82109. var PanoramaToCubeMapTools = /** @class */ (function () {
  82110. function PanoramaToCubeMapTools() {
  82111. }
  82112. /**
  82113. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82114. *
  82115. * @param float32Array The source data.
  82116. * @param inputWidth The width of the input panorama.
  82117. * @param inputhHeight The height of the input panorama.
  82118. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82119. * @return The cubemap data
  82120. */
  82121. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82122. if (!float32Array) {
  82123. throw "ConvertPanoramaToCubemap: input cannot be null";
  82124. }
  82125. if (float32Array.length != inputWidth * inputHeight * 3) {
  82126. throw "ConvertPanoramaToCubemap: input size is wrong";
  82127. }
  82128. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82129. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82130. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82131. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82132. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82133. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82134. return {
  82135. front: textureFront,
  82136. back: textureBack,
  82137. left: textureLeft,
  82138. right: textureRight,
  82139. up: textureUp,
  82140. down: textureDown,
  82141. size: size,
  82142. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82143. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82144. gammaSpace: false,
  82145. };
  82146. };
  82147. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82148. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82149. var textureArray = new Float32Array(buffer);
  82150. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82151. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82152. var dy = 1 / texSize;
  82153. var fy = 0;
  82154. for (var y = 0; y < texSize; y++) {
  82155. var xv1 = faceData[0];
  82156. var xv2 = faceData[2];
  82157. for (var x = 0; x < texSize; x++) {
  82158. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82159. v.normalize();
  82160. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82161. // 3 channels per pixels
  82162. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82163. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82164. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82165. xv1 = xv1.add(rotDX1);
  82166. xv2 = xv2.add(rotDX2);
  82167. }
  82168. fy += dy;
  82169. }
  82170. return textureArray;
  82171. };
  82172. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82173. var theta = Math.atan2(vDir.z, vDir.x);
  82174. var phi = Math.acos(vDir.y);
  82175. while (theta < -Math.PI)
  82176. theta += 2 * Math.PI;
  82177. while (theta > Math.PI)
  82178. theta -= 2 * Math.PI;
  82179. var dx = theta / Math.PI;
  82180. var dy = phi / Math.PI;
  82181. // recenter.
  82182. dx = dx * 0.5 + 0.5;
  82183. var px = Math.round(dx * inputWidth);
  82184. if (px < 0)
  82185. px = 0;
  82186. else if (px >= inputWidth)
  82187. px = inputWidth - 1;
  82188. var py = Math.round(dy * inputHeight);
  82189. if (py < 0)
  82190. py = 0;
  82191. else if (py >= inputHeight)
  82192. py = inputHeight - 1;
  82193. var inputY = (inputHeight - py - 1);
  82194. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82195. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82196. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82197. return {
  82198. r: r,
  82199. g: g,
  82200. b: b
  82201. };
  82202. };
  82203. PanoramaToCubeMapTools.FACE_FRONT = [
  82204. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82205. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82206. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82207. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82208. ];
  82209. PanoramaToCubeMapTools.FACE_BACK = [
  82210. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82211. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82212. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82213. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82214. ];
  82215. PanoramaToCubeMapTools.FACE_RIGHT = [
  82216. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82217. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82218. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82219. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82220. ];
  82221. PanoramaToCubeMapTools.FACE_LEFT = [
  82222. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82223. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82224. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82225. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82226. ];
  82227. PanoramaToCubeMapTools.FACE_DOWN = [
  82228. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82229. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82230. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82231. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82232. ];
  82233. PanoramaToCubeMapTools.FACE_UP = [
  82234. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82235. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82236. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82237. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82238. ];
  82239. return PanoramaToCubeMapTools;
  82240. }());
  82241. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82242. })(BABYLON || (BABYLON = {}));
  82243. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82244. var BABYLON;
  82245. (function (BABYLON) {
  82246. ;
  82247. /**
  82248. * This groups tools to convert HDR texture to native colors array.
  82249. */
  82250. var HDRTools = /** @class */ (function () {
  82251. function HDRTools() {
  82252. }
  82253. HDRTools.Ldexp = function (mantissa, exponent) {
  82254. if (exponent > 1023) {
  82255. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82256. }
  82257. if (exponent < -1074) {
  82258. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82259. }
  82260. return mantissa * Math.pow(2, exponent);
  82261. };
  82262. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82263. if (exponent > 0) { /*nonzero pixel*/
  82264. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82265. float32array[index + 0] = red * exponent;
  82266. float32array[index + 1] = green * exponent;
  82267. float32array[index + 2] = blue * exponent;
  82268. }
  82269. else {
  82270. float32array[index + 0] = 0;
  82271. float32array[index + 1] = 0;
  82272. float32array[index + 2] = 0;
  82273. }
  82274. };
  82275. HDRTools.readStringLine = function (uint8array, startIndex) {
  82276. var line = "";
  82277. var character = "";
  82278. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82279. character = String.fromCharCode(uint8array[i]);
  82280. if (character == "\n") {
  82281. break;
  82282. }
  82283. line += character;
  82284. }
  82285. return line;
  82286. };
  82287. /**
  82288. * Reads header information from an RGBE texture stored in a native array.
  82289. * More information on this format are available here:
  82290. * https://en.wikipedia.org/wiki/RGBE_image_format
  82291. *
  82292. * @param uint8array The binary file stored in native array.
  82293. * @return The header information.
  82294. */
  82295. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82296. var height = 0;
  82297. var width = 0;
  82298. var line = this.readStringLine(uint8array, 0);
  82299. if (line[0] != '#' || line[1] != '?') {
  82300. throw "Bad HDR Format.";
  82301. }
  82302. var endOfHeader = false;
  82303. var findFormat = false;
  82304. var lineIndex = 0;
  82305. do {
  82306. lineIndex += (line.length + 1);
  82307. line = this.readStringLine(uint8array, lineIndex);
  82308. if (line == "FORMAT=32-bit_rle_rgbe") {
  82309. findFormat = true;
  82310. }
  82311. else if (line.length == 0) {
  82312. endOfHeader = true;
  82313. }
  82314. } while (!endOfHeader);
  82315. if (!findFormat) {
  82316. throw "HDR Bad header format, unsupported FORMAT";
  82317. }
  82318. lineIndex += (line.length + 1);
  82319. line = this.readStringLine(uint8array, lineIndex);
  82320. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82321. var match = sizeRegexp.exec(line);
  82322. // TODO. Support +Y and -X if needed.
  82323. if (!match || match.length < 3) {
  82324. throw "HDR Bad header format, no size";
  82325. }
  82326. width = parseInt(match[2]);
  82327. height = parseInt(match[1]);
  82328. if (width < 8 || width > 0x7fff) {
  82329. throw "HDR Bad header format, unsupported size";
  82330. }
  82331. lineIndex += (line.length + 1);
  82332. return {
  82333. height: height,
  82334. width: width,
  82335. dataPosition: lineIndex
  82336. };
  82337. };
  82338. /**
  82339. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82340. * This RGBE texture needs to store the information as a panorama.
  82341. *
  82342. * More information on this format are available here:
  82343. * https://en.wikipedia.org/wiki/RGBE_image_format
  82344. *
  82345. * @param buffer The binary file stored in an array buffer.
  82346. * @param size The expected size of the extracted cubemap.
  82347. * @return The Cube Map information.
  82348. */
  82349. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82350. var uint8array = new Uint8Array(buffer);
  82351. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82352. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82353. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82354. return cubeMapData;
  82355. };
  82356. /**
  82357. * Returns the pixels data extracted from an RGBE texture.
  82358. * This pixels will be stored left to right up to down in the R G B order in one array.
  82359. *
  82360. * More information on this format are available here:
  82361. * https://en.wikipedia.org/wiki/RGBE_image_format
  82362. *
  82363. * @param uint8array The binary file stored in an array buffer.
  82364. * @param hdrInfo The header information of the file.
  82365. * @return The pixels data in RGB right to left up to down order.
  82366. */
  82367. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82368. // Keep for multi format supports.
  82369. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82370. };
  82371. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82372. var num_scanlines = hdrInfo.height;
  82373. var scanline_width = hdrInfo.width;
  82374. var a, b, c, d, count;
  82375. var dataIndex = hdrInfo.dataPosition;
  82376. var index = 0, endIndex = 0, i = 0;
  82377. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82378. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82379. // 3 channels of 4 bytes per pixel in float.
  82380. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82381. var resultArray = new Float32Array(resultBuffer);
  82382. // read in each successive scanline
  82383. while (num_scanlines > 0) {
  82384. a = uint8array[dataIndex++];
  82385. b = uint8array[dataIndex++];
  82386. c = uint8array[dataIndex++];
  82387. d = uint8array[dataIndex++];
  82388. if (a != 2 || b != 2 || (c & 0x80)) {
  82389. // this file is not run length encoded
  82390. throw "HDR Bad header format, not RLE";
  82391. }
  82392. if (((c << 8) | d) != scanline_width) {
  82393. throw "HDR Bad header format, wrong scan line width";
  82394. }
  82395. index = 0;
  82396. // read each of the four channels for the scanline into the buffer
  82397. for (i = 0; i < 4; i++) {
  82398. endIndex = (i + 1) * scanline_width;
  82399. while (index < endIndex) {
  82400. a = uint8array[dataIndex++];
  82401. b = uint8array[dataIndex++];
  82402. if (a > 128) {
  82403. // a run of the same value
  82404. count = a - 128;
  82405. if ((count == 0) || (count > endIndex - index)) {
  82406. throw "HDR Bad Format, bad scanline data (run)";
  82407. }
  82408. while (count-- > 0) {
  82409. scanLineArray[index++] = b;
  82410. }
  82411. }
  82412. else {
  82413. // a non-run
  82414. count = a;
  82415. if ((count == 0) || (count > endIndex - index)) {
  82416. throw "HDR Bad Format, bad scanline data (non-run)";
  82417. }
  82418. scanLineArray[index++] = b;
  82419. if (--count > 0) {
  82420. for (var j = 0; j < count; j++) {
  82421. scanLineArray[index++] = uint8array[dataIndex++];
  82422. }
  82423. }
  82424. }
  82425. }
  82426. }
  82427. // now convert data from buffer into floats
  82428. for (i = 0; i < scanline_width; i++) {
  82429. a = scanLineArray[i];
  82430. b = scanLineArray[i + scanline_width];
  82431. c = scanLineArray[i + 2 * scanline_width];
  82432. d = scanLineArray[i + 3 * scanline_width];
  82433. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82434. }
  82435. num_scanlines--;
  82436. }
  82437. return resultArray;
  82438. };
  82439. return HDRTools;
  82440. }());
  82441. BABYLON.HDRTools = HDRTools;
  82442. })(BABYLON || (BABYLON = {}));
  82443. //# sourceMappingURL=babylon.hdr.js.map
  82444. var BABYLON;
  82445. (function (BABYLON) {
  82446. /**
  82447. * Sets of helpers addressing the serialization and deserialization of environment texture
  82448. * stored in a BabylonJS env file.
  82449. * Those files are usually stored as .env files.
  82450. */
  82451. var EnvironmentTextureTools = /** @class */ (function () {
  82452. function EnvironmentTextureTools() {
  82453. }
  82454. /**
  82455. * Gets the environment info from an env file.
  82456. * @param data The array buffer containing the .env bytes.
  82457. * @returns the environment file info (the json header) if successfully parsed.
  82458. */
  82459. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82460. var dataView = new DataView(data);
  82461. var pos = 0;
  82462. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82463. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82464. BABYLON.Tools.Error('Not a babylon environment map');
  82465. return null;
  82466. }
  82467. }
  82468. // Read json manifest - collect characters up to null terminator
  82469. var manifestString = '';
  82470. var charCode = 0x00;
  82471. while ((charCode = dataView.getUint8(pos++))) {
  82472. manifestString += String.fromCharCode(charCode);
  82473. }
  82474. var manifest = JSON.parse(manifestString);
  82475. if (manifest.specular) {
  82476. // Extend the header with the position of the payload.
  82477. manifest.specular.specularDataPosition = pos;
  82478. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  82479. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  82480. }
  82481. return manifest;
  82482. };
  82483. /**
  82484. * Creates an environment texture from a loaded cube texture.
  82485. * @param texture defines the cube texture to convert in env file
  82486. * @return a promise containing the environment data if succesfull.
  82487. */
  82488. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82489. var _this = this;
  82490. var internalTexture = texture.getInternalTexture();
  82491. if (!internalTexture) {
  82492. return Promise.reject("The cube texture is invalid.");
  82493. }
  82494. if (!texture._prefiltered) {
  82495. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82496. }
  82497. var engine = internalTexture.getEngine();
  82498. if (engine && engine.premultipliedAlpha) {
  82499. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82500. }
  82501. var canvas = engine.getRenderingCanvas();
  82502. if (!canvas) {
  82503. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82504. }
  82505. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82506. if (!engine.getCaps().textureFloatRender) {
  82507. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82508. if (!engine.getCaps().textureHalfFloatRender) {
  82509. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82510. }
  82511. }
  82512. var cubeWidth = internalTexture.width;
  82513. var hostingScene = new BABYLON.Scene(engine);
  82514. var specularTextures = {};
  82515. var promises = [];
  82516. // Read and collect all mipmaps data from the cube.
  82517. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82518. mipmapsCount = Math.round(mipmapsCount);
  82519. var _loop_1 = function (i) {
  82520. var faceWidth = Math.pow(2, mipmapsCount - i);
  82521. var _loop_2 = function (face) {
  82522. var data = texture.readPixels(face, i);
  82523. // Creates a temp texture with the face data.
  82524. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82525. // And rgbdEncode them.
  82526. var promise = new Promise(function (resolve, reject) {
  82527. 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);
  82528. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82529. rgbdPostProcess.onApply = function (effect) {
  82530. effect._bindTexture("textureSampler", tempTexture);
  82531. };
  82532. // As the process needs to happen on the main canvas, keep track of the current size
  82533. var currentW = engine.getRenderWidth();
  82534. var currentH = engine.getRenderHeight();
  82535. // Set the desired size for the texture
  82536. engine.setSize(faceWidth, faceWidth);
  82537. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82538. // Reading datas from WebGL
  82539. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82540. var fileReader = new FileReader();
  82541. fileReader.onload = function (event) {
  82542. var arrayBuffer = event.target.result;
  82543. specularTextures[i * 6 + face] = arrayBuffer;
  82544. resolve();
  82545. };
  82546. fileReader.readAsArrayBuffer(blob);
  82547. });
  82548. // Reapply the previous canvas size
  82549. engine.setSize(currentW, currentH);
  82550. });
  82551. });
  82552. promises.push(promise);
  82553. };
  82554. // All faces of the cube.
  82555. for (var face = 0; face < 6; face++) {
  82556. _loop_2(face);
  82557. }
  82558. };
  82559. for (var i = 0; i <= mipmapsCount; i++) {
  82560. _loop_1(i);
  82561. }
  82562. // Once all the textures haves been collected as RGBD stored in PNGs
  82563. return Promise.all(promises).then(function () {
  82564. // We can delete the hosting scene keeping track of all the creation objects
  82565. hostingScene.dispose();
  82566. // Creates the json header for the env texture
  82567. var info = {
  82568. version: 1,
  82569. width: cubeWidth,
  82570. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82571. specular: {
  82572. mipmaps: [],
  82573. lodGenerationScale: texture.lodGenerationScale
  82574. }
  82575. };
  82576. // Sets the specular image data information
  82577. var position = 0;
  82578. for (var i = 0; i <= mipmapsCount; i++) {
  82579. for (var face = 0; face < 6; face++) {
  82580. var byteLength = specularTextures[i * 6 + face].byteLength;
  82581. info.specular.mipmaps.push({
  82582. length: byteLength,
  82583. position: position
  82584. });
  82585. position += byteLength;
  82586. }
  82587. }
  82588. // Encode the JSON as an array buffer
  82589. var infoString = JSON.stringify(info);
  82590. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82591. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82592. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82593. infoView[i] = infoString.charCodeAt(i);
  82594. }
  82595. // Ends up with a null terminator for easier parsing
  82596. infoView[infoString.length] = 0x00;
  82597. // Computes the final required size and creates the storage
  82598. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82599. var finalBuffer = new ArrayBuffer(totalSize);
  82600. var finalBufferView = new Uint8Array(finalBuffer);
  82601. var dataView = new DataView(finalBuffer);
  82602. // Copy the magic bytes identifying the file in
  82603. var pos = 0;
  82604. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82605. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82606. }
  82607. // Add the json info
  82608. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82609. pos += infoBuffer.byteLength;
  82610. // Finally inserts the texture data
  82611. for (var i = 0; i <= mipmapsCount; i++) {
  82612. for (var face = 0; face < 6; face++) {
  82613. var dataBuffer = specularTextures[i * 6 + face];
  82614. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82615. pos += dataBuffer.byteLength;
  82616. }
  82617. }
  82618. // Voila
  82619. return finalBuffer;
  82620. });
  82621. };
  82622. /**
  82623. * Creates a JSON representation of the spherical data.
  82624. * @param texture defines the texture containing the polynomials
  82625. * @return the JSON representation of the spherical info
  82626. */
  82627. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82628. var polynmials = texture.sphericalPolynomial;
  82629. if (polynmials == null) {
  82630. return null;
  82631. }
  82632. return {
  82633. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82634. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82635. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82636. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82637. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82638. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82639. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82640. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82641. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82642. };
  82643. };
  82644. /**
  82645. * Uploads the texture info contained in the env file to the GPU.
  82646. * @param texture defines the internal texture to upload to
  82647. * @param arrayBuffer defines the buffer cotaining the data to load
  82648. * @param info defines the texture info retrieved through the GetEnvInfo method
  82649. * @returns a promise
  82650. */
  82651. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82652. if (info.version !== 1) {
  82653. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  82654. }
  82655. var specularInfo = info.specular;
  82656. if (!specularInfo) {
  82657. // Nothing else parsed so far
  82658. return Promise.resolve();
  82659. }
  82660. // Double checks the enclosed info
  82661. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82662. mipmapsCount = Math.round(mipmapsCount) + 1;
  82663. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82664. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  82665. }
  82666. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  82667. var imageData = new Array(mipmapsCount);
  82668. for (var i = 0; i < mipmapsCount; i++) {
  82669. imageData[i] = new Array(6);
  82670. for (var face = 0; face < 6; face++) {
  82671. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82672. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82673. }
  82674. }
  82675. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82676. };
  82677. /**
  82678. * Uploads the levels of image data to the GPU.
  82679. * @param texture defines the internal texture to upload to
  82680. * @param imageData defines the array buffer views of image data [mipmap][face]
  82681. * @returns a promise
  82682. */
  82683. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82684. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  82685. throw new Error("Texture size must be a power of two");
  82686. }
  82687. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  82688. // Gets everything ready.
  82689. var engine = texture.getEngine();
  82690. var expandTexture = false;
  82691. var generateNonLODTextures = false;
  82692. var rgbdPostProcess = null;
  82693. var cubeRtt = null;
  82694. var lodTextures = null;
  82695. var caps = engine.getCaps();
  82696. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82697. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82698. texture.generateMipMaps = true;
  82699. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  82700. // Add extra process if texture lod is not supported
  82701. if (!caps.textureLOD) {
  82702. expandTexture = false;
  82703. generateNonLODTextures = true;
  82704. lodTextures = {};
  82705. }
  82706. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82707. else if (engine.webGLVersion < 2) {
  82708. expandTexture = false;
  82709. }
  82710. // If half float available we can uncompress the texture
  82711. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82712. expandTexture = true;
  82713. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82714. }
  82715. // If full float available we can uncompress the texture
  82716. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82717. expandTexture = true;
  82718. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82719. }
  82720. // Expand the texture if possible
  82721. if (expandTexture) {
  82722. // Simply run through the decode PP
  82723. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82724. texture._isRGBD = false;
  82725. texture.invertY = false;
  82726. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82727. generateDepthBuffer: false,
  82728. generateMipMaps: true,
  82729. generateStencilBuffer: false,
  82730. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82731. type: texture.type,
  82732. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82733. });
  82734. }
  82735. else {
  82736. texture._isRGBD = true;
  82737. texture.invertY = true;
  82738. // In case of missing support, applies the same patch than DDS files.
  82739. if (generateNonLODTextures) {
  82740. var mipSlices = 3;
  82741. var scale = texture._lodGenerationScale;
  82742. var offset = texture._lodGenerationOffset;
  82743. for (var i = 0; i < mipSlices; i++) {
  82744. //compute LOD from even spacing in smoothness (matching shader calculation)
  82745. var smoothness = i / (mipSlices - 1);
  82746. var roughness = 1 - smoothness;
  82747. var minLODIndex = offset; // roughness = 0
  82748. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  82749. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82750. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82751. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82752. glTextureFromLod.isCube = true;
  82753. glTextureFromLod.invertY = true;
  82754. glTextureFromLod.generateMipMaps = false;
  82755. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82756. // Wrap in a base texture for easy binding.
  82757. var lodTexture = new BABYLON.BaseTexture(null);
  82758. lodTexture.isCube = true;
  82759. lodTexture._texture = glTextureFromLod;
  82760. lodTextures[mipmapIndex] = lodTexture;
  82761. switch (i) {
  82762. case 0:
  82763. texture._lodTextureLow = lodTexture;
  82764. break;
  82765. case 1:
  82766. texture._lodTextureMid = lodTexture;
  82767. break;
  82768. case 2:
  82769. texture._lodTextureHigh = lodTexture;
  82770. break;
  82771. }
  82772. }
  82773. }
  82774. }
  82775. var promises = [];
  82776. var _loop_3 = function (i) {
  82777. var _loop_4 = function (face) {
  82778. // Constructs an image element from image data
  82779. var bytes = imageData[i][face];
  82780. var blob = new Blob([bytes], { type: 'image/png' });
  82781. var url = URL.createObjectURL(blob);
  82782. var image = new Image();
  82783. image.src = url;
  82784. // Enqueue promise to upload to the texture.
  82785. var promise = new Promise(function (resolve, reject) {
  82786. image.onload = function () {
  82787. if (expandTexture) {
  82788. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82789. reject(message);
  82790. }, image);
  82791. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82792. // Uncompress the data to a RTT
  82793. rgbdPostProcess.onApply = function (effect) {
  82794. effect._bindTexture("textureSampler", tempTexture_1);
  82795. effect.setFloat2("scale", 1, 1);
  82796. };
  82797. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82798. // Cleanup
  82799. engine.restoreDefaultFramebuffer();
  82800. tempTexture_1.dispose();
  82801. window.URL.revokeObjectURL(url);
  82802. resolve();
  82803. });
  82804. }
  82805. else {
  82806. engine._uploadImageToTexture(texture, image, face, i);
  82807. // Upload the face to the non lod texture support
  82808. if (generateNonLODTextures) {
  82809. var lodTexture = lodTextures[i];
  82810. if (lodTexture) {
  82811. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  82812. }
  82813. }
  82814. resolve();
  82815. }
  82816. };
  82817. image.onerror = function (error) {
  82818. reject(error);
  82819. };
  82820. });
  82821. promises.push(promise);
  82822. };
  82823. // All faces
  82824. for (var face = 0; face < 6; face++) {
  82825. _loop_4(face);
  82826. }
  82827. };
  82828. // All mipmaps up to provided number of images
  82829. for (var i = 0; i < imageData.length; i++) {
  82830. _loop_3(i);
  82831. }
  82832. // Fill remaining mipmaps with black textures.
  82833. if (imageData.length < mipmapsCount) {
  82834. var data = void 0;
  82835. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  82836. var dataLength = size * size * 4;
  82837. switch (texture.type) {
  82838. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  82839. data = new Uint8Array(dataLength);
  82840. break;
  82841. }
  82842. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  82843. data = new Uint16Array(dataLength);
  82844. break;
  82845. }
  82846. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  82847. data = new Float32Array(dataLength);
  82848. break;
  82849. }
  82850. }
  82851. for (var i = imageData.length; i < mipmapsCount; i++) {
  82852. for (var face = 0; face < 6; face++) {
  82853. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  82854. }
  82855. }
  82856. }
  82857. // Once all done, finishes the cleanup and return
  82858. return Promise.all(promises).then(function () {
  82859. // Release temp RTT.
  82860. if (cubeRtt) {
  82861. engine._releaseFramebufferObjects(cubeRtt);
  82862. cubeRtt._swapAndDie(texture);
  82863. }
  82864. // Release temp Post Process.
  82865. if (rgbdPostProcess) {
  82866. rgbdPostProcess.dispose();
  82867. }
  82868. // Flag internal texture as ready in case they are in use.
  82869. if (generateNonLODTextures) {
  82870. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82871. texture._lodTextureHigh._texture.isReady = true;
  82872. }
  82873. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82874. texture._lodTextureMid._texture.isReady = true;
  82875. }
  82876. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82877. texture._lodTextureLow._texture.isReady = true;
  82878. }
  82879. }
  82880. });
  82881. };
  82882. /**
  82883. * Uploads spherical polynomials information to the texture.
  82884. * @param texture defines the texture we are trying to upload the information to
  82885. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82886. */
  82887. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  82888. if (info.version !== 1) {
  82889. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82890. }
  82891. var irradianceInfo = info.irradiance;
  82892. if (!irradianceInfo) {
  82893. return;
  82894. }
  82895. var sp = new BABYLON.SphericalPolynomial();
  82896. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  82897. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  82898. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  82899. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  82900. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  82901. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  82902. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  82903. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  82904. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  82905. texture._sphericalPolynomial = sp;
  82906. };
  82907. /**
  82908. * Magic number identifying the env file.
  82909. */
  82910. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82911. return EnvironmentTextureTools;
  82912. }());
  82913. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82914. })(BABYLON || (BABYLON = {}));
  82915. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82916. var BABYLON;
  82917. (function (BABYLON) {
  82918. /**
  82919. * This represents a texture coming from an HDR input.
  82920. *
  82921. * The only supported format is currently panorama picture stored in RGBE format.
  82922. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82923. */
  82924. var HDRCubeTexture = /** @class */ (function (_super) {
  82925. __extends(HDRCubeTexture, _super);
  82926. /**
  82927. * Instantiates an HDRTexture from the following parameters.
  82928. *
  82929. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82930. * @param scene The scene the texture will be used in
  82931. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82932. * @param noMipmap Forces to not generate the mipmap if true
  82933. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82934. * @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)
  82935. * @param reserved Reserved flag for internal use.
  82936. */
  82937. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82938. if (noMipmap === void 0) { noMipmap = false; }
  82939. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82940. if (gammaSpace === void 0) { gammaSpace = false; }
  82941. if (reserved === void 0) { reserved = false; }
  82942. if (onLoad === void 0) { onLoad = null; }
  82943. if (onError === void 0) { onError = null; }
  82944. var _this = _super.call(this, scene) || this;
  82945. _this._generateHarmonics = true;
  82946. _this._onLoad = null;
  82947. _this._onError = null;
  82948. /**
  82949. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82950. */
  82951. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82952. _this._isBlocking = true;
  82953. _this._rotationY = 0;
  82954. /**
  82955. * Gets or sets the center of the bounding box associated with the cube texture
  82956. * It must define where the camera used to render the texture was set
  82957. */
  82958. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82959. if (!url) {
  82960. return _this;
  82961. }
  82962. _this.name = url;
  82963. _this.url = url;
  82964. _this.hasAlpha = false;
  82965. _this.isCube = true;
  82966. _this._textureMatrix = BABYLON.Matrix.Identity();
  82967. _this._onLoad = onLoad;
  82968. _this._onError = onError;
  82969. _this.gammaSpace = gammaSpace;
  82970. _this._noMipmap = noMipmap;
  82971. _this._size = size;
  82972. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82973. if (!_this._texture) {
  82974. if (!scene.useDelayedTextureLoading) {
  82975. _this.loadTexture();
  82976. }
  82977. else {
  82978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82979. }
  82980. }
  82981. return _this;
  82982. }
  82983. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82984. /**
  82985. * Gets wether or not the texture is blocking during loading.
  82986. */
  82987. get: function () {
  82988. return this._isBlocking;
  82989. },
  82990. /**
  82991. * Sets wether or not the texture is blocking during loading.
  82992. */
  82993. set: function (value) {
  82994. this._isBlocking = value;
  82995. },
  82996. enumerable: true,
  82997. configurable: true
  82998. });
  82999. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83000. /**
  83001. * Gets texture matrix rotation angle around Y axis radians.
  83002. */
  83003. get: function () {
  83004. return this._rotationY;
  83005. },
  83006. /**
  83007. * Sets texture matrix rotation angle around Y axis in radians.
  83008. */
  83009. set: function (value) {
  83010. this._rotationY = value;
  83011. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83012. },
  83013. enumerable: true,
  83014. configurable: true
  83015. });
  83016. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83017. get: function () {
  83018. return this._boundingBoxSize;
  83019. },
  83020. /**
  83021. * Gets or sets the size of the bounding box associated with the cube texture
  83022. * When defined, the cubemap will switch to local mode
  83023. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83024. * @example https://www.babylonjs-playground.com/#RNASML
  83025. */
  83026. set: function (value) {
  83027. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83028. return;
  83029. }
  83030. this._boundingBoxSize = value;
  83031. var scene = this.getScene();
  83032. if (scene) {
  83033. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83034. }
  83035. },
  83036. enumerable: true,
  83037. configurable: true
  83038. });
  83039. /**
  83040. * Occurs when the file is raw .hdr file.
  83041. */
  83042. HDRCubeTexture.prototype.loadTexture = function () {
  83043. var _this = this;
  83044. var callback = function (buffer) {
  83045. _this.lodGenerationOffset = 0.0;
  83046. _this.lodGenerationScale = 0.8;
  83047. var scene = _this.getScene();
  83048. if (!scene) {
  83049. return null;
  83050. }
  83051. // Extract the raw linear data.
  83052. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83053. // Generate harmonics if needed.
  83054. if (_this._generateHarmonics) {
  83055. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83056. _this.sphericalPolynomial = sphericalPolynomial;
  83057. }
  83058. var results = [];
  83059. var byteArray = null;
  83060. // Push each faces.
  83061. for (var j = 0; j < 6; j++) {
  83062. // Create uintarray fallback.
  83063. if (!scene.getEngine().getCaps().textureFloat) {
  83064. // 3 channels of 1 bytes per pixel in bytes.
  83065. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83066. byteArray = new Uint8Array(byteBuffer);
  83067. }
  83068. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83069. // If special cases.
  83070. if (_this.gammaSpace || byteArray) {
  83071. for (var i = 0; i < _this._size * _this._size; i++) {
  83072. // Put in gamma space if requested.
  83073. if (_this.gammaSpace) {
  83074. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83075. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83076. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83077. }
  83078. // Convert to int texture for fallback.
  83079. if (byteArray) {
  83080. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83081. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83082. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83083. // May use luminance instead if the result is not accurate.
  83084. var max = Math.max(Math.max(r, g), b);
  83085. if (max > 255) {
  83086. var scale = 255 / max;
  83087. r *= scale;
  83088. g *= scale;
  83089. b *= scale;
  83090. }
  83091. byteArray[(i * 3) + 0] = r;
  83092. byteArray[(i * 3) + 1] = g;
  83093. byteArray[(i * 3) + 2] = b;
  83094. }
  83095. }
  83096. }
  83097. if (byteArray) {
  83098. results.push(byteArray);
  83099. }
  83100. else {
  83101. results.push(dataFace);
  83102. }
  83103. }
  83104. return results;
  83105. };
  83106. var scene = this.getScene();
  83107. if (scene) {
  83108. 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);
  83109. }
  83110. };
  83111. HDRCubeTexture.prototype.clone = function () {
  83112. var scene = this.getScene();
  83113. if (!scene) {
  83114. return this;
  83115. }
  83116. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83117. // Base texture
  83118. newTexture.level = this.level;
  83119. newTexture.wrapU = this.wrapU;
  83120. newTexture.wrapV = this.wrapV;
  83121. newTexture.coordinatesIndex = this.coordinatesIndex;
  83122. newTexture.coordinatesMode = this.coordinatesMode;
  83123. return newTexture;
  83124. };
  83125. // Methods
  83126. HDRCubeTexture.prototype.delayLoad = function () {
  83127. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83128. return;
  83129. }
  83130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83131. this._texture = this._getFromCache(this.url, this._noMipmap);
  83132. if (!this._texture) {
  83133. this.loadTexture();
  83134. }
  83135. };
  83136. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83137. return this._textureMatrix;
  83138. };
  83139. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83140. this._textureMatrix = value;
  83141. };
  83142. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83143. var texture = null;
  83144. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83145. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83146. texture.name = parsedTexture.name;
  83147. texture.hasAlpha = parsedTexture.hasAlpha;
  83148. texture.level = parsedTexture.level;
  83149. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83150. texture.isBlocking = parsedTexture.isBlocking;
  83151. }
  83152. if (texture) {
  83153. if (parsedTexture.boundingBoxPosition) {
  83154. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83155. }
  83156. if (parsedTexture.boundingBoxSize) {
  83157. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83158. }
  83159. if (parsedTexture.rotationY) {
  83160. texture.rotationY = parsedTexture.rotationY;
  83161. }
  83162. }
  83163. return texture;
  83164. };
  83165. HDRCubeTexture.prototype.serialize = function () {
  83166. if (!this.name) {
  83167. return null;
  83168. }
  83169. var serializationObject = {};
  83170. serializationObject.name = this.name;
  83171. serializationObject.hasAlpha = this.hasAlpha;
  83172. serializationObject.isCube = true;
  83173. serializationObject.level = this.level;
  83174. serializationObject.size = this._size;
  83175. serializationObject.coordinatesMode = this.coordinatesMode;
  83176. serializationObject.useInGammaSpace = this.gammaSpace;
  83177. serializationObject.generateHarmonics = this._generateHarmonics;
  83178. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83179. serializationObject.noMipmap = this._noMipmap;
  83180. serializationObject.isBlocking = this._isBlocking;
  83181. serializationObject.rotationY = this._rotationY;
  83182. return serializationObject;
  83183. };
  83184. HDRCubeTexture._facesMapping = [
  83185. "right",
  83186. "left",
  83187. "up",
  83188. "down",
  83189. "front",
  83190. "back"
  83191. ];
  83192. return HDRCubeTexture;
  83193. }(BABYLON.BaseTexture));
  83194. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83195. })(BABYLON || (BABYLON = {}));
  83196. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83197. var BABYLON;
  83198. (function (BABYLON) {
  83199. var IndexedVector2 = /** @class */ (function (_super) {
  83200. __extends(IndexedVector2, _super);
  83201. function IndexedVector2(original, index) {
  83202. var _this = _super.call(this, original.x, original.y) || this;
  83203. _this.index = index;
  83204. return _this;
  83205. }
  83206. return IndexedVector2;
  83207. }(BABYLON.Vector2));
  83208. var PolygonPoints = /** @class */ (function () {
  83209. function PolygonPoints() {
  83210. this.elements = new Array();
  83211. }
  83212. PolygonPoints.prototype.add = function (originalPoints) {
  83213. var _this = this;
  83214. var result = new Array();
  83215. originalPoints.forEach(function (point) {
  83216. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83217. var newPoint = new IndexedVector2(point, _this.elements.length);
  83218. result.push(newPoint);
  83219. _this.elements.push(newPoint);
  83220. }
  83221. });
  83222. return result;
  83223. };
  83224. PolygonPoints.prototype.computeBounds = function () {
  83225. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83226. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83227. this.elements.forEach(function (point) {
  83228. // x
  83229. if (point.x < lmin.x) {
  83230. lmin.x = point.x;
  83231. }
  83232. else if (point.x > lmax.x) {
  83233. lmax.x = point.x;
  83234. }
  83235. // y
  83236. if (point.y < lmin.y) {
  83237. lmin.y = point.y;
  83238. }
  83239. else if (point.y > lmax.y) {
  83240. lmax.y = point.y;
  83241. }
  83242. });
  83243. return {
  83244. min: lmin,
  83245. max: lmax,
  83246. width: lmax.x - lmin.x,
  83247. height: lmax.y - lmin.y
  83248. };
  83249. };
  83250. return PolygonPoints;
  83251. }());
  83252. var Polygon = /** @class */ (function () {
  83253. function Polygon() {
  83254. }
  83255. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83256. return [
  83257. new BABYLON.Vector2(xmin, ymin),
  83258. new BABYLON.Vector2(xmax, ymin),
  83259. new BABYLON.Vector2(xmax, ymax),
  83260. new BABYLON.Vector2(xmin, ymax)
  83261. ];
  83262. };
  83263. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83264. if (cx === void 0) { cx = 0; }
  83265. if (cy === void 0) { cy = 0; }
  83266. if (numberOfSides === void 0) { numberOfSides = 32; }
  83267. var result = new Array();
  83268. var angle = 0;
  83269. var increment = (Math.PI * 2) / numberOfSides;
  83270. for (var i = 0; i < numberOfSides; i++) {
  83271. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83272. angle -= increment;
  83273. }
  83274. return result;
  83275. };
  83276. Polygon.Parse = function (input) {
  83277. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83278. var i, result = [];
  83279. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83280. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83281. }
  83282. return result;
  83283. };
  83284. Polygon.StartingAt = function (x, y) {
  83285. return BABYLON.Path2.StartingAt(x, y);
  83286. };
  83287. return Polygon;
  83288. }());
  83289. BABYLON.Polygon = Polygon;
  83290. var PolygonMeshBuilder = /** @class */ (function () {
  83291. function PolygonMeshBuilder(name, contours, scene) {
  83292. this._points = new PolygonPoints();
  83293. this._outlinepoints = new PolygonPoints();
  83294. this._holes = new Array();
  83295. this._epoints = new Array();
  83296. this._eholes = new Array();
  83297. this._name = name;
  83298. this._scene = scene;
  83299. var points;
  83300. if (contours instanceof BABYLON.Path2) {
  83301. points = contours.getPoints();
  83302. }
  83303. else {
  83304. points = contours;
  83305. }
  83306. this._addToepoint(points);
  83307. this._points.add(points);
  83308. this._outlinepoints.add(points);
  83309. if (typeof earcut === 'undefined') {
  83310. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83311. }
  83312. }
  83313. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83314. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83315. var p = points_1[_i];
  83316. this._epoints.push(p.x, p.y);
  83317. }
  83318. };
  83319. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83320. this._points.add(hole);
  83321. var holepoints = new PolygonPoints();
  83322. holepoints.add(hole);
  83323. this._holes.push(holepoints);
  83324. this._eholes.push(this._epoints.length / 2);
  83325. this._addToepoint(hole);
  83326. return this;
  83327. };
  83328. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83329. var _this = this;
  83330. if (updatable === void 0) { updatable = false; }
  83331. if (depth === void 0) { depth = 0; }
  83332. var result = new BABYLON.Mesh(this._name, this._scene);
  83333. var normals = new Array();
  83334. var positions = new Array();
  83335. var uvs = new Array();
  83336. var bounds = this._points.computeBounds();
  83337. this._points.elements.forEach(function (p) {
  83338. normals.push(0, 1.0, 0);
  83339. positions.push(p.x, 0, p.y);
  83340. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83341. });
  83342. var indices = new Array();
  83343. var res = earcut(this._epoints, this._eholes, 2);
  83344. for (var i = 0; i < res.length; i++) {
  83345. indices.push(res[i]);
  83346. }
  83347. if (depth > 0) {
  83348. var positionscount = (positions.length / 3); //get the current pointcount
  83349. this._points.elements.forEach(function (p) {
  83350. normals.push(0, -1.0, 0);
  83351. positions.push(p.x, -depth, p.y);
  83352. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83353. });
  83354. var totalCount = indices.length;
  83355. for (var i = 0; i < totalCount; i += 3) {
  83356. var i0 = indices[i + 0];
  83357. var i1 = indices[i + 1];
  83358. var i2 = indices[i + 2];
  83359. indices.push(i2 + positionscount);
  83360. indices.push(i1 + positionscount);
  83361. indices.push(i0 + positionscount);
  83362. }
  83363. //Add the sides
  83364. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83365. this._holes.forEach(function (hole) {
  83366. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83367. });
  83368. }
  83369. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83370. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83371. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83372. result.setIndices(indices);
  83373. return result;
  83374. };
  83375. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83376. var StartIndex = positions.length / 3;
  83377. var ulength = 0;
  83378. for (var i = 0; i < points.elements.length; i++) {
  83379. var p = points.elements[i];
  83380. var p1;
  83381. if ((i + 1) > points.elements.length - 1) {
  83382. p1 = points.elements[0];
  83383. }
  83384. else {
  83385. p1 = points.elements[i + 1];
  83386. }
  83387. positions.push(p.x, 0, p.y);
  83388. positions.push(p.x, -depth, p.y);
  83389. positions.push(p1.x, 0, p1.y);
  83390. positions.push(p1.x, -depth, p1.y);
  83391. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83392. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83393. var v3 = v2.subtract(v1);
  83394. var v4 = new BABYLON.Vector3(0, 1, 0);
  83395. var vn = BABYLON.Vector3.Cross(v3, v4);
  83396. vn = vn.normalize();
  83397. uvs.push(ulength / bounds.width, 0);
  83398. uvs.push(ulength / bounds.width, 1);
  83399. ulength += v3.length();
  83400. uvs.push((ulength / bounds.width), 0);
  83401. uvs.push((ulength / bounds.width), 1);
  83402. if (!flip) {
  83403. normals.push(-vn.x, -vn.y, -vn.z);
  83404. normals.push(-vn.x, -vn.y, -vn.z);
  83405. normals.push(-vn.x, -vn.y, -vn.z);
  83406. normals.push(-vn.x, -vn.y, -vn.z);
  83407. indices.push(StartIndex);
  83408. indices.push(StartIndex + 1);
  83409. indices.push(StartIndex + 2);
  83410. indices.push(StartIndex + 1);
  83411. indices.push(StartIndex + 3);
  83412. indices.push(StartIndex + 2);
  83413. }
  83414. else {
  83415. normals.push(vn.x, vn.y, vn.z);
  83416. normals.push(vn.x, vn.y, vn.z);
  83417. normals.push(vn.x, vn.y, vn.z);
  83418. normals.push(vn.x, vn.y, vn.z);
  83419. indices.push(StartIndex);
  83420. indices.push(StartIndex + 2);
  83421. indices.push(StartIndex + 1);
  83422. indices.push(StartIndex + 1);
  83423. indices.push(StartIndex + 2);
  83424. indices.push(StartIndex + 3);
  83425. }
  83426. StartIndex += 4;
  83427. }
  83428. ;
  83429. };
  83430. return PolygonMeshBuilder;
  83431. }());
  83432. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83433. })(BABYLON || (BABYLON = {}));
  83434. //# sourceMappingURL=babylon.polygonMesh.js.map
  83435. var BABYLON;
  83436. (function (BABYLON) {
  83437. // Unique ID when we import meshes from Babylon to CSG
  83438. var currentCSGMeshId = 0;
  83439. // # class Vertex
  83440. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83441. // one to provide additional features like texture coordinates and vertex
  83442. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83443. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83444. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83445. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83446. // is not used anywhere else.
  83447. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83448. var Vertex = /** @class */ (function () {
  83449. function Vertex(pos, normal, uv) {
  83450. this.pos = pos;
  83451. this.normal = normal;
  83452. this.uv = uv;
  83453. }
  83454. Vertex.prototype.clone = function () {
  83455. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83456. };
  83457. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83458. // orientation of a polygon is flipped.
  83459. Vertex.prototype.flip = function () {
  83460. this.normal = this.normal.scale(-1);
  83461. };
  83462. // Create a new vertex between this vertex and `other` by linearly
  83463. // interpolating all properties using a parameter of `t`. Subclasses should
  83464. // override this to interpolate additional properties.
  83465. Vertex.prototype.interpolate = function (other, t) {
  83466. 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));
  83467. };
  83468. return Vertex;
  83469. }());
  83470. // # class Plane
  83471. // Represents a plane in 3D space.
  83472. var Plane = /** @class */ (function () {
  83473. function Plane(normal, w) {
  83474. this.normal = normal;
  83475. this.w = w;
  83476. }
  83477. Plane.FromPoints = function (a, b, c) {
  83478. var v0 = c.subtract(a);
  83479. var v1 = b.subtract(a);
  83480. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83481. return null;
  83482. }
  83483. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83484. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83485. };
  83486. Plane.prototype.clone = function () {
  83487. return new Plane(this.normal.clone(), this.w);
  83488. };
  83489. Plane.prototype.flip = function () {
  83490. this.normal.scaleInPlace(-1);
  83491. this.w = -this.w;
  83492. };
  83493. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83494. // fragments in the appropriate lists. Coplanar polygons go into either
  83495. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83496. // respect to this plane. Polygons in front or in back of this plane go into
  83497. // either `front` or `back`.
  83498. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83499. var COPLANAR = 0;
  83500. var FRONT = 1;
  83501. var BACK = 2;
  83502. var SPANNING = 3;
  83503. // Classify each point as well as the entire polygon into one of the above
  83504. // four classes.
  83505. var polygonType = 0;
  83506. var types = [];
  83507. var i;
  83508. var t;
  83509. for (i = 0; i < polygon.vertices.length; i++) {
  83510. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83511. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83512. polygonType |= type;
  83513. types.push(type);
  83514. }
  83515. // Put the polygon in the correct list, splitting it when necessary.
  83516. switch (polygonType) {
  83517. case COPLANAR:
  83518. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83519. break;
  83520. case FRONT:
  83521. front.push(polygon);
  83522. break;
  83523. case BACK:
  83524. back.push(polygon);
  83525. break;
  83526. case SPANNING:
  83527. var f = [], b = [];
  83528. for (i = 0; i < polygon.vertices.length; i++) {
  83529. var j = (i + 1) % polygon.vertices.length;
  83530. var ti = types[i], tj = types[j];
  83531. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83532. if (ti !== BACK)
  83533. f.push(vi);
  83534. if (ti !== FRONT)
  83535. b.push(ti !== BACK ? vi.clone() : vi);
  83536. if ((ti | tj) === SPANNING) {
  83537. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83538. var v = vi.interpolate(vj, t);
  83539. f.push(v);
  83540. b.push(v.clone());
  83541. }
  83542. }
  83543. var poly;
  83544. if (f.length >= 3) {
  83545. poly = new Polygon(f, polygon.shared);
  83546. if (poly.plane)
  83547. front.push(poly);
  83548. }
  83549. if (b.length >= 3) {
  83550. poly = new Polygon(b, polygon.shared);
  83551. if (poly.plane)
  83552. back.push(poly);
  83553. }
  83554. break;
  83555. }
  83556. };
  83557. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83558. // point is on the plane.
  83559. Plane.EPSILON = 1e-5;
  83560. return Plane;
  83561. }());
  83562. // # class Polygon
  83563. // Represents a convex polygon. The vertices used to initialize a polygon must
  83564. // be coplanar and form a convex loop.
  83565. //
  83566. // Each convex polygon has a `shared` property, which is shared between all
  83567. // polygons that are clones of each other or were split from the same polygon.
  83568. // This can be used to define per-polygon properties (such as surface color).
  83569. var Polygon = /** @class */ (function () {
  83570. function Polygon(vertices, shared) {
  83571. this.vertices = vertices;
  83572. this.shared = shared;
  83573. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83574. }
  83575. Polygon.prototype.clone = function () {
  83576. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83577. return new Polygon(vertices, this.shared);
  83578. };
  83579. Polygon.prototype.flip = function () {
  83580. this.vertices.reverse().map(function (v) { v.flip(); });
  83581. this.plane.flip();
  83582. };
  83583. return Polygon;
  83584. }());
  83585. // # class Node
  83586. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83587. // by picking a polygon to split along. That polygon (and all other coplanar
  83588. // polygons) are added directly to that node and the other polygons are added to
  83589. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83590. // no distinction between internal and leaf nodes.
  83591. var Node = /** @class */ (function () {
  83592. function Node(polygons) {
  83593. this.plane = null;
  83594. this.front = null;
  83595. this.back = null;
  83596. this.polygons = new Array();
  83597. if (polygons) {
  83598. this.build(polygons);
  83599. }
  83600. }
  83601. Node.prototype.clone = function () {
  83602. var node = new Node();
  83603. node.plane = this.plane && this.plane.clone();
  83604. node.front = this.front && this.front.clone();
  83605. node.back = this.back && this.back.clone();
  83606. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83607. return node;
  83608. };
  83609. // Convert solid space to empty space and empty space to solid space.
  83610. Node.prototype.invert = function () {
  83611. for (var i = 0; i < this.polygons.length; i++) {
  83612. this.polygons[i].flip();
  83613. }
  83614. if (this.plane) {
  83615. this.plane.flip();
  83616. }
  83617. if (this.front) {
  83618. this.front.invert();
  83619. }
  83620. if (this.back) {
  83621. this.back.invert();
  83622. }
  83623. var temp = this.front;
  83624. this.front = this.back;
  83625. this.back = temp;
  83626. };
  83627. // Recursively remove all polygons in `polygons` that are inside this BSP
  83628. // tree.
  83629. Node.prototype.clipPolygons = function (polygons) {
  83630. if (!this.plane)
  83631. return polygons.slice();
  83632. var front = new Array(), back = new Array();
  83633. for (var i = 0; i < polygons.length; i++) {
  83634. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83635. }
  83636. if (this.front) {
  83637. front = this.front.clipPolygons(front);
  83638. }
  83639. if (this.back) {
  83640. back = this.back.clipPolygons(back);
  83641. }
  83642. else {
  83643. back = [];
  83644. }
  83645. return front.concat(back);
  83646. };
  83647. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83648. // `bsp`.
  83649. Node.prototype.clipTo = function (bsp) {
  83650. this.polygons = bsp.clipPolygons(this.polygons);
  83651. if (this.front)
  83652. this.front.clipTo(bsp);
  83653. if (this.back)
  83654. this.back.clipTo(bsp);
  83655. };
  83656. // Return a list of all polygons in this BSP tree.
  83657. Node.prototype.allPolygons = function () {
  83658. var polygons = this.polygons.slice();
  83659. if (this.front)
  83660. polygons = polygons.concat(this.front.allPolygons());
  83661. if (this.back)
  83662. polygons = polygons.concat(this.back.allPolygons());
  83663. return polygons;
  83664. };
  83665. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83666. // new polygons are filtered down to the bottom of the tree and become new
  83667. // nodes there. Each set of polygons is partitioned using the first polygon
  83668. // (no heuristic is used to pick a good split).
  83669. Node.prototype.build = function (polygons) {
  83670. if (!polygons.length)
  83671. return;
  83672. if (!this.plane)
  83673. this.plane = polygons[0].plane.clone();
  83674. var front = new Array(), back = new Array();
  83675. for (var i = 0; i < polygons.length; i++) {
  83676. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83677. }
  83678. if (front.length) {
  83679. if (!this.front)
  83680. this.front = new Node();
  83681. this.front.build(front);
  83682. }
  83683. if (back.length) {
  83684. if (!this.back)
  83685. this.back = new Node();
  83686. this.back.build(back);
  83687. }
  83688. };
  83689. return Node;
  83690. }());
  83691. var CSG = /** @class */ (function () {
  83692. function CSG() {
  83693. this.polygons = new Array();
  83694. }
  83695. // Convert BABYLON.Mesh to BABYLON.CSG
  83696. CSG.FromMesh = function (mesh) {
  83697. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83698. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83699. if (mesh instanceof BABYLON.Mesh) {
  83700. mesh.computeWorldMatrix(true);
  83701. matrix = mesh.getWorldMatrix();
  83702. meshPosition = mesh.position.clone();
  83703. meshRotation = mesh.rotation.clone();
  83704. if (mesh.rotationQuaternion) {
  83705. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83706. }
  83707. meshScaling = mesh.scaling.clone();
  83708. }
  83709. else {
  83710. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83711. }
  83712. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83713. var subMeshes = mesh.subMeshes;
  83714. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83715. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83716. vertices = [];
  83717. for (var j = 0; j < 3; j++) {
  83718. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83719. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83720. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83721. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83722. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83723. vertex = new Vertex(position, normal, uv);
  83724. vertices.push(vertex);
  83725. }
  83726. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83727. // To handle the case of degenerated triangle
  83728. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83729. if (polygon.plane)
  83730. polygons.push(polygon);
  83731. }
  83732. }
  83733. var csg = CSG.FromPolygons(polygons);
  83734. csg.matrix = matrix;
  83735. csg.position = meshPosition;
  83736. csg.rotation = meshRotation;
  83737. csg.scaling = meshScaling;
  83738. csg.rotationQuaternion = meshRotationQuaternion;
  83739. currentCSGMeshId++;
  83740. return csg;
  83741. };
  83742. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83743. CSG.FromPolygons = function (polygons) {
  83744. var csg = new CSG();
  83745. csg.polygons = polygons;
  83746. return csg;
  83747. };
  83748. CSG.prototype.clone = function () {
  83749. var csg = new CSG();
  83750. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83751. csg.copyTransformAttributes(this);
  83752. return csg;
  83753. };
  83754. CSG.prototype.union = function (csg) {
  83755. var a = new Node(this.clone().polygons);
  83756. var b = new Node(csg.clone().polygons);
  83757. a.clipTo(b);
  83758. b.clipTo(a);
  83759. b.invert();
  83760. b.clipTo(a);
  83761. b.invert();
  83762. a.build(b.allPolygons());
  83763. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83764. };
  83765. CSG.prototype.unionInPlace = function (csg) {
  83766. var a = new Node(this.polygons);
  83767. var b = new Node(csg.polygons);
  83768. a.clipTo(b);
  83769. b.clipTo(a);
  83770. b.invert();
  83771. b.clipTo(a);
  83772. b.invert();
  83773. a.build(b.allPolygons());
  83774. this.polygons = a.allPolygons();
  83775. };
  83776. CSG.prototype.subtract = function (csg) {
  83777. var a = new Node(this.clone().polygons);
  83778. var b = new Node(csg.clone().polygons);
  83779. a.invert();
  83780. a.clipTo(b);
  83781. b.clipTo(a);
  83782. b.invert();
  83783. b.clipTo(a);
  83784. b.invert();
  83785. a.build(b.allPolygons());
  83786. a.invert();
  83787. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83788. };
  83789. CSG.prototype.subtractInPlace = function (csg) {
  83790. var a = new Node(this.polygons);
  83791. var b = new Node(csg.polygons);
  83792. a.invert();
  83793. a.clipTo(b);
  83794. b.clipTo(a);
  83795. b.invert();
  83796. b.clipTo(a);
  83797. b.invert();
  83798. a.build(b.allPolygons());
  83799. a.invert();
  83800. this.polygons = a.allPolygons();
  83801. };
  83802. CSG.prototype.intersect = function (csg) {
  83803. var a = new Node(this.clone().polygons);
  83804. var b = new Node(csg.clone().polygons);
  83805. a.invert();
  83806. b.clipTo(a);
  83807. b.invert();
  83808. a.clipTo(b);
  83809. b.clipTo(a);
  83810. a.build(b.allPolygons());
  83811. a.invert();
  83812. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83813. };
  83814. CSG.prototype.intersectInPlace = function (csg) {
  83815. var a = new Node(this.polygons);
  83816. var b = new Node(csg.polygons);
  83817. a.invert();
  83818. b.clipTo(a);
  83819. b.invert();
  83820. a.clipTo(b);
  83821. b.clipTo(a);
  83822. a.build(b.allPolygons());
  83823. a.invert();
  83824. this.polygons = a.allPolygons();
  83825. };
  83826. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83827. // not modified.
  83828. CSG.prototype.inverse = function () {
  83829. var csg = this.clone();
  83830. csg.inverseInPlace();
  83831. return csg;
  83832. };
  83833. CSG.prototype.inverseInPlace = function () {
  83834. this.polygons.map(function (p) { p.flip(); });
  83835. };
  83836. // This is used to keep meshes transformations so they can be restored
  83837. // when we build back a Babylon Mesh
  83838. // NB : All CSG operations are performed in world coordinates
  83839. CSG.prototype.copyTransformAttributes = function (csg) {
  83840. this.matrix = csg.matrix;
  83841. this.position = csg.position;
  83842. this.rotation = csg.rotation;
  83843. this.scaling = csg.scaling;
  83844. this.rotationQuaternion = csg.rotationQuaternion;
  83845. return this;
  83846. };
  83847. // Build Raw mesh from CSG
  83848. // Coordinates here are in world space
  83849. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83850. var matrix = this.matrix.clone();
  83851. matrix.invert();
  83852. 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;
  83853. if (keepSubMeshes) {
  83854. // Sort Polygons, since subMeshes are indices range
  83855. polygons.sort(function (a, b) {
  83856. if (a.shared.meshId === b.shared.meshId) {
  83857. return a.shared.subMeshId - b.shared.subMeshId;
  83858. }
  83859. else {
  83860. return a.shared.meshId - b.shared.meshId;
  83861. }
  83862. });
  83863. }
  83864. for (var i = 0, il = polygons.length; i < il; i++) {
  83865. polygon = polygons[i];
  83866. // Building SubMeshes
  83867. if (!subMesh_dict[polygon.shared.meshId]) {
  83868. subMesh_dict[polygon.shared.meshId] = {};
  83869. }
  83870. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83871. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83872. indexStart: +Infinity,
  83873. indexEnd: -Infinity,
  83874. materialIndex: polygon.shared.materialIndex
  83875. };
  83876. }
  83877. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83878. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83879. polygonIndices[0] = 0;
  83880. polygonIndices[1] = j - 1;
  83881. polygonIndices[2] = j;
  83882. for (var k = 0; k < 3; k++) {
  83883. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83884. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83885. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83886. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83887. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83888. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83889. // Check if 2 points can be merged
  83890. if (!(typeof vertex_idx !== 'undefined' &&
  83891. normals[vertex_idx * 3] === localNormal.x &&
  83892. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83893. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83894. uvs[vertex_idx * 2] === uv.x &&
  83895. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83896. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83897. uvs.push(uv.x, uv.y);
  83898. normals.push(normal.x, normal.y, normal.z);
  83899. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83900. }
  83901. indices.push(vertex_idx);
  83902. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83903. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83904. currentIndex++;
  83905. }
  83906. }
  83907. }
  83908. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83909. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83910. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83911. mesh.setIndices(indices, null);
  83912. if (keepSubMeshes) {
  83913. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83914. var materialIndexOffset = 0, materialMaxIndex;
  83915. mesh.subMeshes = new Array();
  83916. for (var m in subMesh_dict) {
  83917. materialMaxIndex = -1;
  83918. for (var sm in subMesh_dict[m]) {
  83919. subMesh_obj = subMesh_dict[m][sm];
  83920. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83921. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83922. }
  83923. materialIndexOffset += ++materialMaxIndex;
  83924. }
  83925. }
  83926. return mesh;
  83927. };
  83928. // Build Mesh from CSG taking material and transforms into account
  83929. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83930. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83931. mesh.material = material;
  83932. mesh.position.copyFrom(this.position);
  83933. mesh.rotation.copyFrom(this.rotation);
  83934. if (this.rotationQuaternion) {
  83935. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83936. }
  83937. mesh.scaling.copyFrom(this.scaling);
  83938. mesh.computeWorldMatrix(true);
  83939. return mesh;
  83940. };
  83941. return CSG;
  83942. }());
  83943. BABYLON.CSG = CSG;
  83944. })(BABYLON || (BABYLON = {}));
  83945. //# sourceMappingURL=babylon.csg.js.map
  83946. var BABYLON;
  83947. (function (BABYLON) {
  83948. var LensFlare = /** @class */ (function () {
  83949. function LensFlare(size, position, color, imgUrl, system) {
  83950. this.size = size;
  83951. this.position = position;
  83952. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83953. this.color = color || new BABYLON.Color3(1, 1, 1);
  83954. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83955. this._system = system;
  83956. system.lensFlares.push(this);
  83957. }
  83958. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83959. return new LensFlare(size, position, color, imgUrl, system);
  83960. };
  83961. LensFlare.prototype.dispose = function () {
  83962. if (this.texture) {
  83963. this.texture.dispose();
  83964. }
  83965. // Remove from scene
  83966. var index = this._system.lensFlares.indexOf(this);
  83967. this._system.lensFlares.splice(index, 1);
  83968. };
  83969. ;
  83970. return LensFlare;
  83971. }());
  83972. BABYLON.LensFlare = LensFlare;
  83973. })(BABYLON || (BABYLON = {}));
  83974. //# sourceMappingURL=babylon.lensFlare.js.map
  83975. var BABYLON;
  83976. (function (BABYLON) {
  83977. // Adds the parser to the scene parsers.
  83978. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  83979. // Lens flares
  83980. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  83981. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  83982. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  83983. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  83984. container.lensFlareSystems.push(lf);
  83985. }
  83986. }
  83987. });
  83988. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  83989. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83990. if (this.lensFlareSystems[index].name === name) {
  83991. return this.lensFlareSystems[index];
  83992. }
  83993. }
  83994. return null;
  83995. };
  83996. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  83997. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83998. if (this.lensFlareSystems[index].id === id) {
  83999. return this.lensFlareSystems[index];
  84000. }
  84001. }
  84002. return null;
  84003. };
  84004. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84005. var index = this.lensFlareSystems.indexOf(toRemove);
  84006. if (index !== -1) {
  84007. this.lensFlareSystems.splice(index, 1);
  84008. }
  84009. return index;
  84010. };
  84011. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84012. this.lensFlareSystems.push(newLensFlareSystem);
  84013. };
  84014. /**
  84015. * Defines the lens flare scene component responsible to manage any lens flares
  84016. * in a given scene.
  84017. */
  84018. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84019. /**
  84020. * Creates a new instance of the component for the given scene
  84021. * @param scene Defines the scene to register the component in
  84022. */
  84023. function LensFlareSystemSceneComponent(scene) {
  84024. /**
  84025. * The component name helpfull to identify the component in the list of scene components.
  84026. */
  84027. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84028. this.scene = scene;
  84029. scene.lensFlareSystems = new Array();
  84030. }
  84031. /**
  84032. * Registers the component in a given scene
  84033. */
  84034. LensFlareSystemSceneComponent.prototype.register = function () {
  84035. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84036. };
  84037. /**
  84038. * Rebuilds the elements related to this component in case of
  84039. * context lost for instance.
  84040. */
  84041. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84042. // Nothing to do for lens flare
  84043. };
  84044. /**
  84045. * Adds all the element from the container to the scene
  84046. * @param container the container holding the elements
  84047. */
  84048. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84049. var _this = this;
  84050. if (!container.lensFlareSystems) {
  84051. return;
  84052. }
  84053. container.lensFlareSystems.forEach(function (o) {
  84054. _this.scene.addLensFlareSystem(o);
  84055. });
  84056. };
  84057. /**
  84058. * Removes all the elements in the container from the scene
  84059. * @param container contains the elements to remove
  84060. */
  84061. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84062. var _this = this;
  84063. if (!container.lensFlareSystems) {
  84064. return;
  84065. }
  84066. container.lensFlareSystems.forEach(function (o) {
  84067. _this.scene.removeLensFlareSystem(o);
  84068. });
  84069. };
  84070. /**
  84071. * Serializes the component data to the specified json object
  84072. * @param serializationObject The object to serialize to
  84073. */
  84074. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84075. // Lens flares
  84076. serializationObject.lensFlareSystems = [];
  84077. var lensFlareSystems = this.scene.lensFlareSystems;
  84078. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84079. var lensFlareSystem = lensFlareSystems_1[_i];
  84080. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84081. }
  84082. };
  84083. /**
  84084. * Disposes the component and the associated ressources.
  84085. */
  84086. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84087. var lensFlareSystems = this.scene.lensFlareSystems;
  84088. while (lensFlareSystems.length) {
  84089. lensFlareSystems[0].dispose();
  84090. }
  84091. };
  84092. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84093. // Lens flares
  84094. if (this.scene.lensFlaresEnabled) {
  84095. var lensFlareSystems = this.scene.lensFlareSystems;
  84096. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84097. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84098. var lensFlareSystem = lensFlareSystems_2[_i];
  84099. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84100. lensFlareSystem.render();
  84101. }
  84102. }
  84103. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84104. }
  84105. };
  84106. return LensFlareSystemSceneComponent;
  84107. }());
  84108. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84109. })(BABYLON || (BABYLON = {}));
  84110. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84111. var BABYLON;
  84112. (function (BABYLON) {
  84113. var LensFlareSystem = /** @class */ (function () {
  84114. function LensFlareSystem(name, emitter, scene) {
  84115. this.name = name;
  84116. this.lensFlares = new Array();
  84117. this.borderLimit = 300;
  84118. this.viewportBorder = 0;
  84119. this.layerMask = 0x0FFFFFFF;
  84120. this._vertexBuffers = {};
  84121. this._isEnabled = true;
  84122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84123. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84124. if (!component) {
  84125. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84126. scene._addComponent(component);
  84127. }
  84128. this._emitter = emitter;
  84129. this.id = name;
  84130. scene.lensFlareSystems.push(this);
  84131. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84132. var engine = scene.getEngine();
  84133. // VBO
  84134. var vertices = [];
  84135. vertices.push(1, 1);
  84136. vertices.push(-1, 1);
  84137. vertices.push(-1, -1);
  84138. vertices.push(1, -1);
  84139. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84140. // Indices
  84141. var indices = [];
  84142. indices.push(0);
  84143. indices.push(1);
  84144. indices.push(2);
  84145. indices.push(0);
  84146. indices.push(2);
  84147. indices.push(3);
  84148. this._indexBuffer = engine.createIndexBuffer(indices);
  84149. // Effects
  84150. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84151. }
  84152. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84153. get: function () {
  84154. return this._isEnabled;
  84155. },
  84156. set: function (value) {
  84157. this._isEnabled = value;
  84158. },
  84159. enumerable: true,
  84160. configurable: true
  84161. });
  84162. LensFlareSystem.prototype.getScene = function () {
  84163. return this._scene;
  84164. };
  84165. LensFlareSystem.prototype.getEmitter = function () {
  84166. return this._emitter;
  84167. };
  84168. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84169. this._emitter = newEmitter;
  84170. };
  84171. LensFlareSystem.prototype.getEmitterPosition = function () {
  84172. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84173. };
  84174. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84175. var position = this.getEmitterPosition();
  84176. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84177. this._positionX = position.x;
  84178. this._positionY = position.y;
  84179. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84180. if (this.viewportBorder > 0) {
  84181. globalViewport.x -= this.viewportBorder;
  84182. globalViewport.y -= this.viewportBorder;
  84183. globalViewport.width += this.viewportBorder * 2;
  84184. globalViewport.height += this.viewportBorder * 2;
  84185. position.x += this.viewportBorder;
  84186. position.y += this.viewportBorder;
  84187. this._positionX += this.viewportBorder;
  84188. this._positionY += this.viewportBorder;
  84189. }
  84190. if (position.z > 0) {
  84191. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84192. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84193. return true;
  84194. }
  84195. return true;
  84196. }
  84197. return false;
  84198. };
  84199. LensFlareSystem.prototype._isVisible = function () {
  84200. if (!this._isEnabled || !this._scene.activeCamera) {
  84201. return false;
  84202. }
  84203. var emitterPosition = this.getEmitterPosition();
  84204. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84205. var distance = direction.length();
  84206. direction.normalize();
  84207. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84208. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84209. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84210. };
  84211. LensFlareSystem.prototype.render = function () {
  84212. if (!this._effect.isReady() || !this._scene.activeCamera)
  84213. return false;
  84214. var engine = this._scene.getEngine();
  84215. var viewport = this._scene.activeCamera.viewport;
  84216. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84217. // Position
  84218. if (!this.computeEffectivePosition(globalViewport)) {
  84219. return false;
  84220. }
  84221. // Visibility
  84222. if (!this._isVisible()) {
  84223. return false;
  84224. }
  84225. // Intensity
  84226. var awayX;
  84227. var awayY;
  84228. if (this._positionX < this.borderLimit + globalViewport.x) {
  84229. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84230. }
  84231. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84232. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84233. }
  84234. else {
  84235. awayX = 0;
  84236. }
  84237. if (this._positionY < this.borderLimit + globalViewport.y) {
  84238. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84239. }
  84240. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84241. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84242. }
  84243. else {
  84244. awayY = 0;
  84245. }
  84246. var away = (awayX > awayY) ? awayX : awayY;
  84247. away -= this.viewportBorder;
  84248. if (away > this.borderLimit) {
  84249. away = this.borderLimit;
  84250. }
  84251. var intensity = 1.0 - (away / this.borderLimit);
  84252. if (intensity < 0) {
  84253. return false;
  84254. }
  84255. if (intensity > 1.0) {
  84256. intensity = 1.0;
  84257. }
  84258. if (this.viewportBorder > 0) {
  84259. globalViewport.x += this.viewportBorder;
  84260. globalViewport.y += this.viewportBorder;
  84261. globalViewport.width -= this.viewportBorder * 2;
  84262. globalViewport.height -= this.viewportBorder * 2;
  84263. this._positionX -= this.viewportBorder;
  84264. this._positionY -= this.viewportBorder;
  84265. }
  84266. // Position
  84267. var centerX = globalViewport.x + globalViewport.width / 2;
  84268. var centerY = globalViewport.y + globalViewport.height / 2;
  84269. var distX = centerX - this._positionX;
  84270. var distY = centerY - this._positionY;
  84271. // Effects
  84272. engine.enableEffect(this._effect);
  84273. engine.setState(false);
  84274. engine.setDepthBuffer(false);
  84275. // VBOs
  84276. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84277. // Flares
  84278. for (var index = 0; index < this.lensFlares.length; index++) {
  84279. var flare = this.lensFlares[index];
  84280. engine.setAlphaMode(flare.alphaMode);
  84281. var x = centerX - (distX * flare.position);
  84282. var y = centerY - (distY * flare.position);
  84283. var cw = flare.size;
  84284. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84285. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84286. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84287. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84288. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84289. // Texture
  84290. this._effect.setTexture("textureSampler", flare.texture);
  84291. // Color
  84292. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84293. // Draw order
  84294. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84295. }
  84296. engine.setDepthBuffer(true);
  84297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84298. return true;
  84299. };
  84300. LensFlareSystem.prototype.dispose = function () {
  84301. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84302. if (vertexBuffer) {
  84303. vertexBuffer.dispose();
  84304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84305. }
  84306. if (this._indexBuffer) {
  84307. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84308. this._indexBuffer = null;
  84309. }
  84310. while (this.lensFlares.length) {
  84311. this.lensFlares[0].dispose();
  84312. }
  84313. // Remove from scene
  84314. var index = this._scene.lensFlareSystems.indexOf(this);
  84315. this._scene.lensFlareSystems.splice(index, 1);
  84316. };
  84317. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84318. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84319. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84320. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84321. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84322. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84323. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84324. var parsedFlare = parsedLensFlareSystem.flares[index];
  84325. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84326. }
  84327. return lensFlareSystem;
  84328. };
  84329. LensFlareSystem.prototype.serialize = function () {
  84330. var serializationObject = {};
  84331. serializationObject.id = this.id;
  84332. serializationObject.name = this.name;
  84333. serializationObject.emitterId = this.getEmitter().id;
  84334. serializationObject.borderLimit = this.borderLimit;
  84335. serializationObject.flares = [];
  84336. for (var index = 0; index < this.lensFlares.length; index++) {
  84337. var flare = this.lensFlares[index];
  84338. serializationObject.flares.push({
  84339. size: flare.size,
  84340. position: flare.position,
  84341. color: flare.color.asArray(),
  84342. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84343. });
  84344. }
  84345. return serializationObject;
  84346. };
  84347. return LensFlareSystem;
  84348. }());
  84349. BABYLON.LensFlareSystem = LensFlareSystem;
  84350. })(BABYLON || (BABYLON = {}));
  84351. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84352. var BABYLON;
  84353. (function (BABYLON) {
  84354. /**
  84355. * This is a holder class for the physics joint created by the physics plugin.
  84356. * It holds a set of functions to control the underlying joint.
  84357. */
  84358. var PhysicsJoint = /** @class */ (function () {
  84359. function PhysicsJoint(type, jointData) {
  84360. this.type = type;
  84361. this.jointData = jointData;
  84362. jointData.nativeParams = jointData.nativeParams || {};
  84363. }
  84364. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84365. get: function () {
  84366. return this._physicsJoint;
  84367. },
  84368. set: function (newJoint) {
  84369. if (this._physicsJoint) {
  84370. //remove from the wolrd
  84371. }
  84372. this._physicsJoint = newJoint;
  84373. },
  84374. enumerable: true,
  84375. configurable: true
  84376. });
  84377. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84378. set: function (physicsPlugin) {
  84379. this._physicsPlugin = physicsPlugin;
  84380. },
  84381. enumerable: true,
  84382. configurable: true
  84383. });
  84384. /**
  84385. * Execute a function that is physics-plugin specific.
  84386. * @param {Function} func the function that will be executed.
  84387. * It accepts two parameters: the physics world and the physics joint.
  84388. */
  84389. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84390. func(this._physicsPlugin.world, this._physicsJoint);
  84391. };
  84392. //TODO check if the native joints are the same
  84393. //Joint Types
  84394. PhysicsJoint.DistanceJoint = 0;
  84395. PhysicsJoint.HingeJoint = 1;
  84396. PhysicsJoint.BallAndSocketJoint = 2;
  84397. PhysicsJoint.WheelJoint = 3;
  84398. PhysicsJoint.SliderJoint = 4;
  84399. //OIMO
  84400. PhysicsJoint.PrismaticJoint = 5;
  84401. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84402. PhysicsJoint.UniversalJoint = 6;
  84403. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84404. //Cannon
  84405. //Similar to a Ball-Joint. Different in params
  84406. PhysicsJoint.PointToPointJoint = 8;
  84407. //Cannon only at the moment
  84408. PhysicsJoint.SpringJoint = 9;
  84409. PhysicsJoint.LockJoint = 10;
  84410. return PhysicsJoint;
  84411. }());
  84412. BABYLON.PhysicsJoint = PhysicsJoint;
  84413. /**
  84414. * A class representing a physics distance joint.
  84415. */
  84416. var DistanceJoint = /** @class */ (function (_super) {
  84417. __extends(DistanceJoint, _super);
  84418. function DistanceJoint(jointData) {
  84419. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84420. }
  84421. /**
  84422. * Update the predefined distance.
  84423. */
  84424. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84425. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84426. };
  84427. return DistanceJoint;
  84428. }(PhysicsJoint));
  84429. BABYLON.DistanceJoint = DistanceJoint;
  84430. var MotorEnabledJoint = /** @class */ (function (_super) {
  84431. __extends(MotorEnabledJoint, _super);
  84432. function MotorEnabledJoint(type, jointData) {
  84433. return _super.call(this, type, jointData) || this;
  84434. }
  84435. /**
  84436. * Set the motor values.
  84437. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84438. * @param {number} force the force to apply
  84439. * @param {number} maxForce max force for this motor.
  84440. */
  84441. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84442. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84443. };
  84444. /**
  84445. * Set the motor's limits.
  84446. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84447. */
  84448. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84449. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84450. };
  84451. return MotorEnabledJoint;
  84452. }(PhysicsJoint));
  84453. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84454. /**
  84455. * This class represents a single hinge physics joint
  84456. */
  84457. var HingeJoint = /** @class */ (function (_super) {
  84458. __extends(HingeJoint, _super);
  84459. function HingeJoint(jointData) {
  84460. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84461. }
  84462. /**
  84463. * Set the motor values.
  84464. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84465. * @param {number} force the force to apply
  84466. * @param {number} maxForce max force for this motor.
  84467. */
  84468. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84469. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84470. };
  84471. /**
  84472. * Set the motor's limits.
  84473. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84474. */
  84475. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84476. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84477. };
  84478. return HingeJoint;
  84479. }(MotorEnabledJoint));
  84480. BABYLON.HingeJoint = HingeJoint;
  84481. /**
  84482. * This class represents a dual hinge physics joint (same as wheel joint)
  84483. */
  84484. var Hinge2Joint = /** @class */ (function (_super) {
  84485. __extends(Hinge2Joint, _super);
  84486. function Hinge2Joint(jointData) {
  84487. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84488. }
  84489. /**
  84490. * Set the motor values.
  84491. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84492. * @param {number} force the force to apply
  84493. * @param {number} maxForce max force for this motor.
  84494. * @param {motorIndex} the motor's index, 0 or 1.
  84495. */
  84496. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84497. if (motorIndex === void 0) { motorIndex = 0; }
  84498. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84499. };
  84500. /**
  84501. * Set the motor limits.
  84502. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84503. * @param {number} upperLimit the upper limit
  84504. * @param {number} lowerLimit lower limit
  84505. * @param {motorIndex} the motor's index, 0 or 1.
  84506. */
  84507. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84508. if (motorIndex === void 0) { motorIndex = 0; }
  84509. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84510. };
  84511. return Hinge2Joint;
  84512. }(MotorEnabledJoint));
  84513. BABYLON.Hinge2Joint = Hinge2Joint;
  84514. })(BABYLON || (BABYLON = {}));
  84515. //# sourceMappingURL=babylon.physicsJoint.js.map
  84516. var BABYLON;
  84517. (function (BABYLON) {
  84518. var PhysicsImpostor = /** @class */ (function () {
  84519. function PhysicsImpostor(object, type, _options, _scene) {
  84520. if (_options === void 0) { _options = { mass: 0 }; }
  84521. var _this = this;
  84522. this.object = object;
  84523. this.type = type;
  84524. this._options = _options;
  84525. this._scene = _scene;
  84526. this._bodyUpdateRequired = false;
  84527. this._onBeforePhysicsStepCallbacks = new Array();
  84528. this._onAfterPhysicsStepCallbacks = new Array();
  84529. this._onPhysicsCollideCallbacks = [];
  84530. this._deltaPosition = BABYLON.Vector3.Zero();
  84531. this._isDisposed = false;
  84532. //temp variables for parent rotation calculations
  84533. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84534. this._tmpQuat = new BABYLON.Quaternion();
  84535. this._tmpQuat2 = new BABYLON.Quaternion();
  84536. /**
  84537. * this function is executed by the physics engine.
  84538. */
  84539. this.beforeStep = function () {
  84540. if (!_this._physicsEngine) {
  84541. return;
  84542. }
  84543. _this.object.translate(_this._deltaPosition, -1);
  84544. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84545. _this.object.computeWorldMatrix(false);
  84546. if (_this.object.parent && _this.object.rotationQuaternion) {
  84547. _this.getParentsRotation();
  84548. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84549. }
  84550. else {
  84551. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84552. }
  84553. if (!_this._options.disableBidirectionalTransformation) {
  84554. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84555. }
  84556. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84557. func(_this);
  84558. });
  84559. };
  84560. /**
  84561. * this function is executed by the physics engine.
  84562. */
  84563. this.afterStep = function () {
  84564. if (!_this._physicsEngine) {
  84565. return;
  84566. }
  84567. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84568. func(_this);
  84569. });
  84570. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84571. // object has now its world rotation. needs to be converted to local.
  84572. if (_this.object.parent && _this.object.rotationQuaternion) {
  84573. _this.getParentsRotation();
  84574. _this._tmpQuat.conjugateInPlace();
  84575. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84576. }
  84577. // take the position set and make it the absolute position of this object.
  84578. _this.object.setAbsolutePosition(_this.object.position);
  84579. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84580. _this.object.translate(_this._deltaPosition, 1);
  84581. };
  84582. /**
  84583. * Legacy collision detection event support
  84584. */
  84585. this.onCollideEvent = null;
  84586. //event and body object due to cannon's event-based architecture.
  84587. this.onCollide = function (e) {
  84588. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84589. return;
  84590. }
  84591. if (!_this._physicsEngine) {
  84592. return;
  84593. }
  84594. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84595. if (otherImpostor) {
  84596. // Legacy collision detection event support
  84597. if (_this.onCollideEvent) {
  84598. _this.onCollideEvent(_this, otherImpostor);
  84599. }
  84600. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84601. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84602. }).forEach(function (obj) {
  84603. obj.callback(_this, otherImpostor);
  84604. });
  84605. }
  84606. };
  84607. //sanity check!
  84608. if (!this.object) {
  84609. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84610. return;
  84611. }
  84612. //legacy support for old syntax.
  84613. if (!this._scene && object.getScene) {
  84614. this._scene = object.getScene();
  84615. }
  84616. if (!this._scene) {
  84617. return;
  84618. }
  84619. this._physicsEngine = this._scene.getPhysicsEngine();
  84620. if (!this._physicsEngine) {
  84621. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84622. }
  84623. else {
  84624. //set the object's quaternion, if not set
  84625. if (!this.object.rotationQuaternion) {
  84626. if (this.object.rotation) {
  84627. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84628. }
  84629. else {
  84630. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84631. }
  84632. }
  84633. //default options params
  84634. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84635. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84636. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84637. this._joints = [];
  84638. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84639. if (!this.object.parent || this._options.ignoreParent) {
  84640. this._init();
  84641. }
  84642. else if (this.object.parent.physicsImpostor) {
  84643. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84644. }
  84645. }
  84646. }
  84647. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84648. get: function () {
  84649. return this._isDisposed;
  84650. },
  84651. enumerable: true,
  84652. configurable: true
  84653. });
  84654. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84655. get: function () {
  84656. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84657. },
  84658. set: function (value) {
  84659. this.setMass(value);
  84660. },
  84661. enumerable: true,
  84662. configurable: true
  84663. });
  84664. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84665. get: function () {
  84666. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84667. },
  84668. set: function (value) {
  84669. if (!this._physicsEngine) {
  84670. return;
  84671. }
  84672. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84673. },
  84674. enumerable: true,
  84675. configurable: true
  84676. });
  84677. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84678. get: function () {
  84679. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84680. },
  84681. set: function (value) {
  84682. if (!this._physicsEngine) {
  84683. return;
  84684. }
  84685. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84686. },
  84687. enumerable: true,
  84688. configurable: true
  84689. });
  84690. /**
  84691. * This function will completly initialize this impostor.
  84692. * It will create a new body - but only if this mesh has no parent.
  84693. * If it has, this impostor will not be used other than to define the impostor
  84694. * of the child mesh.
  84695. */
  84696. PhysicsImpostor.prototype._init = function () {
  84697. if (!this._physicsEngine) {
  84698. return;
  84699. }
  84700. this._physicsEngine.removeImpostor(this);
  84701. this.physicsBody = null;
  84702. this._parent = this._parent || this._getPhysicsParent();
  84703. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84704. this._physicsEngine.addImpostor(this);
  84705. }
  84706. };
  84707. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84708. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84709. var parentMesh = this.object.parent;
  84710. return parentMesh.physicsImpostor;
  84711. }
  84712. return null;
  84713. };
  84714. /**
  84715. * Should a new body be generated.
  84716. */
  84717. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84718. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84719. };
  84720. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84721. this.forceUpdate();
  84722. };
  84723. /**
  84724. * Force a regeneration of this or the parent's impostor's body.
  84725. * Use under cautious - This will remove all joints already implemented.
  84726. */
  84727. PhysicsImpostor.prototype.forceUpdate = function () {
  84728. this._init();
  84729. if (this.parent && !this._options.ignoreParent) {
  84730. this.parent.forceUpdate();
  84731. }
  84732. };
  84733. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84734. /*public get mesh(): AbstractMesh {
  84735. return this._mesh;
  84736. }*/
  84737. /**
  84738. * Gets the body that holds this impostor. Either its own, or its parent.
  84739. */
  84740. get: function () {
  84741. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84742. },
  84743. /**
  84744. * Set the physics body. Used mainly by the physics engine/plugin
  84745. */
  84746. set: function (physicsBody) {
  84747. if (this._physicsBody && this._physicsEngine) {
  84748. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84749. }
  84750. this._physicsBody = physicsBody;
  84751. this.resetUpdateFlags();
  84752. },
  84753. enumerable: true,
  84754. configurable: true
  84755. });
  84756. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84757. get: function () {
  84758. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84759. },
  84760. set: function (value) {
  84761. this._parent = value;
  84762. },
  84763. enumerable: true,
  84764. configurable: true
  84765. });
  84766. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84767. this._bodyUpdateRequired = false;
  84768. };
  84769. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84770. if (this.object.getBoundingInfo) {
  84771. var q = this.object.rotationQuaternion;
  84772. //reset rotation
  84773. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84774. //calculate the world matrix with no rotation
  84775. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84776. var boundingInfo = this.object.getBoundingInfo();
  84777. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84778. //bring back the rotation
  84779. this.object.rotationQuaternion = q;
  84780. //calculate the world matrix with the new rotation
  84781. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84782. return size;
  84783. }
  84784. else {
  84785. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84786. }
  84787. };
  84788. PhysicsImpostor.prototype.getObjectCenter = function () {
  84789. if (this.object.getBoundingInfo) {
  84790. var boundingInfo = this.object.getBoundingInfo();
  84791. return boundingInfo.boundingBox.centerWorld;
  84792. }
  84793. else {
  84794. return this.object.position;
  84795. }
  84796. };
  84797. /**
  84798. * Get a specific parametes from the options parameter.
  84799. */
  84800. PhysicsImpostor.prototype.getParam = function (paramName) {
  84801. return this._options[paramName];
  84802. };
  84803. /**
  84804. * Sets a specific parameter in the options given to the physics plugin
  84805. */
  84806. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84807. this._options[paramName] = value;
  84808. this._bodyUpdateRequired = true;
  84809. };
  84810. /**
  84811. * Specifically change the body's mass option. Won't recreate the physics body object
  84812. */
  84813. PhysicsImpostor.prototype.setMass = function (mass) {
  84814. if (this.getParam("mass") !== mass) {
  84815. this.setParam("mass", mass);
  84816. }
  84817. if (this._physicsEngine) {
  84818. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84819. }
  84820. };
  84821. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84822. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84823. };
  84824. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84825. if (this._physicsEngine) {
  84826. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84827. }
  84828. };
  84829. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84830. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84831. };
  84832. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84833. if (this._physicsEngine) {
  84834. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84835. }
  84836. };
  84837. /**
  84838. * Execute a function with the physics plugin native code.
  84839. * Provide a function the will have two variables - the world object and the physics body object.
  84840. */
  84841. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84842. if (this._physicsEngine) {
  84843. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84844. }
  84845. };
  84846. /**
  84847. * Register a function that will be executed before the physics world is stepping forward.
  84848. */
  84849. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84850. this._onBeforePhysicsStepCallbacks.push(func);
  84851. };
  84852. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84853. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84854. if (index > -1) {
  84855. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84856. }
  84857. else {
  84858. BABYLON.Tools.Warn("Function to remove was not found");
  84859. }
  84860. };
  84861. /**
  84862. * Register a function that will be executed after the physics step
  84863. */
  84864. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84865. this._onAfterPhysicsStepCallbacks.push(func);
  84866. };
  84867. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84868. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84869. if (index > -1) {
  84870. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84871. }
  84872. else {
  84873. BABYLON.Tools.Warn("Function to remove was not found");
  84874. }
  84875. };
  84876. /**
  84877. * register a function that will be executed when this impostor collides against a different body.
  84878. */
  84879. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84880. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84881. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84882. };
  84883. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84884. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84885. var index = -1;
  84886. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84887. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84888. // chcek the arrays match
  84889. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84890. return collidedAgainstList.indexOf(impostor) > -1;
  84891. });
  84892. if (sameList) {
  84893. index = idx;
  84894. }
  84895. return sameList;
  84896. }
  84897. return false;
  84898. });
  84899. if (found) {
  84900. this._onPhysicsCollideCallbacks.splice(index, 1);
  84901. }
  84902. else {
  84903. BABYLON.Tools.Warn("Function to remove was not found");
  84904. }
  84905. };
  84906. PhysicsImpostor.prototype.getParentsRotation = function () {
  84907. var parent = this.object.parent;
  84908. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84909. while (parent) {
  84910. if (parent.rotationQuaternion) {
  84911. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84912. }
  84913. else {
  84914. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84915. }
  84916. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84917. parent = parent.parent;
  84918. }
  84919. return this._tmpQuat;
  84920. };
  84921. /**
  84922. * Apply a force
  84923. */
  84924. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84925. if (this._physicsEngine) {
  84926. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84927. }
  84928. return this;
  84929. };
  84930. /**
  84931. * Apply an impulse
  84932. */
  84933. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84934. if (this._physicsEngine) {
  84935. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84936. }
  84937. return this;
  84938. };
  84939. /**
  84940. * A help function to create a joint.
  84941. */
  84942. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84943. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84944. this.addJoint(otherImpostor, joint);
  84945. return this;
  84946. };
  84947. /**
  84948. * Add a joint to this impostor with a different impostor.
  84949. */
  84950. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84951. this._joints.push({
  84952. otherImpostor: otherImpostor,
  84953. joint: joint
  84954. });
  84955. if (this._physicsEngine) {
  84956. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84957. }
  84958. return this;
  84959. };
  84960. /**
  84961. * Will keep this body still, in a sleep mode.
  84962. */
  84963. PhysicsImpostor.prototype.sleep = function () {
  84964. if (this._physicsEngine) {
  84965. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84966. }
  84967. return this;
  84968. };
  84969. /**
  84970. * Wake the body up.
  84971. */
  84972. PhysicsImpostor.prototype.wakeUp = function () {
  84973. if (this._physicsEngine) {
  84974. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84975. }
  84976. return this;
  84977. };
  84978. PhysicsImpostor.prototype.clone = function (newObject) {
  84979. if (!newObject)
  84980. return null;
  84981. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84982. };
  84983. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84984. var _this = this;
  84985. //no dispose if no physics engine is available.
  84986. if (!this._physicsEngine) {
  84987. return;
  84988. }
  84989. this._joints.forEach(function (j) {
  84990. if (_this._physicsEngine) {
  84991. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84992. }
  84993. });
  84994. //dispose the physics body
  84995. this._physicsEngine.removeImpostor(this);
  84996. if (this.parent) {
  84997. this.parent.forceUpdate();
  84998. }
  84999. else {
  85000. /*this._object.getChildMeshes().forEach(function(mesh) {
  85001. if (mesh.physicsImpostor) {
  85002. if (disposeChildren) {
  85003. mesh.physicsImpostor.dispose();
  85004. mesh.physicsImpostor = null;
  85005. }
  85006. }
  85007. })*/
  85008. }
  85009. this._isDisposed = true;
  85010. };
  85011. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85012. this._deltaPosition.copyFrom(position);
  85013. };
  85014. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85015. if (!this._deltaRotation) {
  85016. this._deltaRotation = new BABYLON.Quaternion();
  85017. }
  85018. this._deltaRotation.copyFrom(rotation);
  85019. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85020. };
  85021. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85022. if (this._physicsEngine) {
  85023. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85024. }
  85025. return this;
  85026. };
  85027. PhysicsImpostor.prototype.getRadius = function () {
  85028. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85029. };
  85030. /**
  85031. * Sync a bone with this impostor
  85032. * @param bone The bone to sync to the impostor.
  85033. * @param boneMesh The mesh that the bone is influencing.
  85034. * @param jointPivot The pivot of the joint / bone in local space.
  85035. * @param distToJoint Optional distance from the impostor to the joint.
  85036. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85037. */
  85038. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85039. var tempVec = PhysicsImpostor._tmpVecs[0];
  85040. var mesh = this.object;
  85041. if (mesh.rotationQuaternion) {
  85042. if (adjustRotation) {
  85043. var tempQuat = PhysicsImpostor._tmpQuat;
  85044. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85045. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85046. }
  85047. else {
  85048. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85049. }
  85050. }
  85051. tempVec.x = 0;
  85052. tempVec.y = 0;
  85053. tempVec.z = 0;
  85054. if (jointPivot) {
  85055. tempVec.x = jointPivot.x;
  85056. tempVec.y = jointPivot.y;
  85057. tempVec.z = jointPivot.z;
  85058. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85059. if (distToJoint === undefined || distToJoint === null) {
  85060. distToJoint = jointPivot.length();
  85061. }
  85062. tempVec.x *= distToJoint;
  85063. tempVec.y *= distToJoint;
  85064. tempVec.z *= distToJoint;
  85065. }
  85066. if (bone.getParent()) {
  85067. tempVec.addInPlace(mesh.getAbsolutePosition());
  85068. bone.setAbsolutePosition(tempVec, boneMesh);
  85069. }
  85070. else {
  85071. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85072. boneMesh.position.x -= tempVec.x;
  85073. boneMesh.position.y -= tempVec.y;
  85074. boneMesh.position.z -= tempVec.z;
  85075. }
  85076. };
  85077. /**
  85078. * Sync impostor to a bone
  85079. * @param bone The bone that the impostor will be synced to.
  85080. * @param boneMesh The mesh that the bone is influencing.
  85081. * @param jointPivot The pivot of the joint / bone in local space.
  85082. * @param distToJoint Optional distance from the impostor to the joint.
  85083. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85084. * @param boneAxis Optional vector3 axis the bone is aligned with
  85085. */
  85086. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85087. var mesh = this.object;
  85088. if (mesh.rotationQuaternion) {
  85089. if (adjustRotation) {
  85090. var tempQuat = PhysicsImpostor._tmpQuat;
  85091. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85092. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85093. }
  85094. else {
  85095. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85096. }
  85097. }
  85098. var pos = PhysicsImpostor._tmpVecs[0];
  85099. var boneDir = PhysicsImpostor._tmpVecs[1];
  85100. if (!boneAxis) {
  85101. boneAxis = PhysicsImpostor._tmpVecs[2];
  85102. boneAxis.x = 0;
  85103. boneAxis.y = 1;
  85104. boneAxis.z = 0;
  85105. }
  85106. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85107. bone.getAbsolutePositionToRef(boneMesh, pos);
  85108. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85109. distToJoint = jointPivot.length();
  85110. }
  85111. if (distToJoint !== undefined && distToJoint !== null) {
  85112. pos.x += boneDir.x * distToJoint;
  85113. pos.y += boneDir.y * distToJoint;
  85114. pos.z += boneDir.z * distToJoint;
  85115. }
  85116. mesh.setAbsolutePosition(pos);
  85117. };
  85118. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85119. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85120. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85121. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85122. //Impostor types
  85123. PhysicsImpostor.NoImpostor = 0;
  85124. PhysicsImpostor.SphereImpostor = 1;
  85125. PhysicsImpostor.BoxImpostor = 2;
  85126. PhysicsImpostor.PlaneImpostor = 3;
  85127. PhysicsImpostor.MeshImpostor = 4;
  85128. PhysicsImpostor.CylinderImpostor = 7;
  85129. PhysicsImpostor.ParticleImpostor = 8;
  85130. PhysicsImpostor.HeightmapImpostor = 9;
  85131. return PhysicsImpostor;
  85132. }());
  85133. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85134. })(BABYLON || (BABYLON = {}));
  85135. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85136. var BABYLON;
  85137. (function (BABYLON) {
  85138. var PhysicsEngine = /** @class */ (function () {
  85139. function PhysicsEngine(gravity, _physicsPlugin) {
  85140. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85141. this._physicsPlugin = _physicsPlugin;
  85142. //new methods and parameters
  85143. this._impostors = [];
  85144. this._joints = [];
  85145. if (!this._physicsPlugin.isSupported()) {
  85146. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85147. + "Please make sure it is included.");
  85148. }
  85149. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85150. this.setGravity(gravity);
  85151. this.setTimeStep();
  85152. }
  85153. PhysicsEngine.prototype.setGravity = function (gravity) {
  85154. this.gravity = gravity;
  85155. this._physicsPlugin.setGravity(this.gravity);
  85156. };
  85157. /**
  85158. * Set the time step of the physics engine.
  85159. * default is 1/60.
  85160. * To slow it down, enter 1/600 for example.
  85161. * To speed it up, 1/30
  85162. * @param {number} newTimeStep the new timestep to apply to this world.
  85163. */
  85164. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85165. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85166. this._physicsPlugin.setTimeStep(newTimeStep);
  85167. };
  85168. /**
  85169. * Get the time step of the physics engine.
  85170. */
  85171. PhysicsEngine.prototype.getTimeStep = function () {
  85172. return this._physicsPlugin.getTimeStep();
  85173. };
  85174. PhysicsEngine.prototype.dispose = function () {
  85175. this._impostors.forEach(function (impostor) {
  85176. impostor.dispose();
  85177. });
  85178. this._physicsPlugin.dispose();
  85179. };
  85180. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85181. return this._physicsPlugin.name;
  85182. };
  85183. /**
  85184. * Adding a new impostor for the impostor tracking.
  85185. * This will be done by the impostor itself.
  85186. * @param {PhysicsImpostor} impostor the impostor to add
  85187. */
  85188. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85189. impostor.uniqueId = this._impostors.push(impostor);
  85190. //if no parent, generate the body
  85191. if (!impostor.parent) {
  85192. this._physicsPlugin.generatePhysicsBody(impostor);
  85193. }
  85194. };
  85195. /**
  85196. * Remove an impostor from the engine.
  85197. * This impostor and its mesh will not longer be updated by the physics engine.
  85198. * @param {PhysicsImpostor} impostor the impostor to remove
  85199. */
  85200. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85201. var index = this._impostors.indexOf(impostor);
  85202. if (index > -1) {
  85203. var removed = this._impostors.splice(index, 1);
  85204. //Is it needed?
  85205. if (removed.length) {
  85206. //this will also remove it from the world.
  85207. removed[0].physicsBody = null;
  85208. }
  85209. }
  85210. };
  85211. /**
  85212. * Add a joint to the physics engine
  85213. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85214. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85215. * @param {PhysicsJoint} the joint that will connect both impostors.
  85216. */
  85217. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85218. var impostorJoint = {
  85219. mainImpostor: mainImpostor,
  85220. connectedImpostor: connectedImpostor,
  85221. joint: joint
  85222. };
  85223. joint.physicsPlugin = this._physicsPlugin;
  85224. this._joints.push(impostorJoint);
  85225. this._physicsPlugin.generateJoint(impostorJoint);
  85226. };
  85227. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85228. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85229. return (impostorJoint.connectedImpostor === connectedImpostor
  85230. && impostorJoint.joint === joint
  85231. && impostorJoint.mainImpostor === mainImpostor);
  85232. });
  85233. if (matchingJoints.length) {
  85234. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85235. //TODO remove it from the list as well
  85236. }
  85237. };
  85238. /**
  85239. * Called by the scene. no need to call it.
  85240. */
  85241. PhysicsEngine.prototype._step = function (delta) {
  85242. var _this = this;
  85243. //check if any mesh has no body / requires an update
  85244. this._impostors.forEach(function (impostor) {
  85245. if (impostor.isBodyInitRequired()) {
  85246. _this._physicsPlugin.generatePhysicsBody(impostor);
  85247. }
  85248. });
  85249. if (delta > 0.1) {
  85250. delta = 0.1;
  85251. }
  85252. else if (delta <= 0) {
  85253. delta = 1.0 / 60.0;
  85254. }
  85255. this._physicsPlugin.executeStep(delta, this._impostors);
  85256. };
  85257. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85258. return this._physicsPlugin;
  85259. };
  85260. PhysicsEngine.prototype.getImpostors = function () {
  85261. return this._impostors;
  85262. };
  85263. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85264. for (var i = 0; i < this._impostors.length; ++i) {
  85265. if (this._impostors[i].object === object) {
  85266. return this._impostors[i];
  85267. }
  85268. }
  85269. return null;
  85270. };
  85271. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85272. for (var i = 0; i < this._impostors.length; ++i) {
  85273. if (this._impostors[i].physicsBody === body) {
  85274. return this._impostors[i];
  85275. }
  85276. }
  85277. return null;
  85278. };
  85279. // Statics
  85280. PhysicsEngine.Epsilon = 0.001;
  85281. return PhysicsEngine;
  85282. }());
  85283. BABYLON.PhysicsEngine = PhysicsEngine;
  85284. })(BABYLON || (BABYLON = {}));
  85285. //# sourceMappingURL=babylon.physicsEngine.js.map
  85286. var BABYLON;
  85287. (function (BABYLON) {
  85288. var PhysicsHelper = /** @class */ (function () {
  85289. function PhysicsHelper(scene) {
  85290. this._scene = scene;
  85291. this._physicsEngine = this._scene.getPhysicsEngine();
  85292. if (!this._physicsEngine) {
  85293. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85294. }
  85295. }
  85296. /**
  85297. * @param {Vector3} origin the origin of the explosion
  85298. * @param {number} radius the explosion radius
  85299. * @param {number} strength the explosion strength
  85300. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85301. */
  85302. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85303. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85304. if (!this._physicsEngine) {
  85305. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85306. return null;
  85307. }
  85308. var impostors = this._physicsEngine.getImpostors();
  85309. if (impostors.length === 0) {
  85310. return null;
  85311. }
  85312. var event = new PhysicsRadialExplosionEvent(this._scene);
  85313. impostors.forEach(function (impostor) {
  85314. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85315. if (!impostorForceAndContactPoint) {
  85316. return;
  85317. }
  85318. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85319. });
  85320. event.dispose(false);
  85321. return event;
  85322. };
  85323. /**
  85324. * @param {Vector3} origin the origin of the explosion
  85325. * @param {number} radius the explosion radius
  85326. * @param {number} strength the explosion strength
  85327. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85328. */
  85329. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85330. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85331. if (!this._physicsEngine) {
  85332. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85333. return null;
  85334. }
  85335. var impostors = this._physicsEngine.getImpostors();
  85336. if (impostors.length === 0) {
  85337. return null;
  85338. }
  85339. var event = new PhysicsRadialExplosionEvent(this._scene);
  85340. impostors.forEach(function (impostor) {
  85341. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85342. if (!impostorForceAndContactPoint) {
  85343. return;
  85344. }
  85345. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85346. });
  85347. event.dispose(false);
  85348. return event;
  85349. };
  85350. /**
  85351. * @param {Vector3} origin the origin of the explosion
  85352. * @param {number} radius the explosion radius
  85353. * @param {number} strength the explosion strength
  85354. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85355. */
  85356. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85357. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85358. if (!this._physicsEngine) {
  85359. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85360. return null;
  85361. }
  85362. var impostors = this._physicsEngine.getImpostors();
  85363. if (impostors.length === 0) {
  85364. return null;
  85365. }
  85366. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85367. event.dispose(false);
  85368. return event;
  85369. };
  85370. /**
  85371. * @param {Vector3} origin the origin of the updraft
  85372. * @param {number} radius the radius of the updraft
  85373. * @param {number} strength the strength of the updraft
  85374. * @param {number} height the height of the updraft
  85375. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85376. */
  85377. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85378. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85379. if (!this._physicsEngine) {
  85380. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85381. return null;
  85382. }
  85383. if (this._physicsEngine.getImpostors().length === 0) {
  85384. return null;
  85385. }
  85386. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85387. event.dispose(false);
  85388. return event;
  85389. };
  85390. /**
  85391. * @param {Vector3} origin the of the vortex
  85392. * @param {number} radius the radius of the vortex
  85393. * @param {number} strength the strength of the vortex
  85394. * @param {number} height the height of the vortex
  85395. */
  85396. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85397. if (!this._physicsEngine) {
  85398. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85399. return null;
  85400. }
  85401. if (this._physicsEngine.getImpostors().length === 0) {
  85402. return null;
  85403. }
  85404. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85405. event.dispose(false);
  85406. return event;
  85407. };
  85408. return PhysicsHelper;
  85409. }());
  85410. BABYLON.PhysicsHelper = PhysicsHelper;
  85411. /***** Radial explosion *****/
  85412. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85413. function PhysicsRadialExplosionEvent(scene) {
  85414. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85415. this._rays = [];
  85416. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85417. this._scene = scene;
  85418. }
  85419. /**
  85420. * Returns the data related to the radial explosion event (sphere & rays).
  85421. * @returns {PhysicsRadialExplosionEventData}
  85422. */
  85423. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85424. this._dataFetched = true;
  85425. return {
  85426. sphere: this._sphere,
  85427. rays: this._rays,
  85428. };
  85429. };
  85430. /**
  85431. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85432. * @param impostor
  85433. * @param {Vector3} origin the origin of the explosion
  85434. * @param {number} radius the explosion radius
  85435. * @param {number} strength the explosion strength
  85436. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85437. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85438. */
  85439. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85440. if (impostor.mass === 0) {
  85441. return null;
  85442. }
  85443. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85444. return null;
  85445. }
  85446. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85447. return null;
  85448. }
  85449. var impostorObjectCenter = impostor.getObjectCenter();
  85450. var direction = impostorObjectCenter.subtract(origin);
  85451. var ray = new BABYLON.Ray(origin, direction, radius);
  85452. this._rays.push(ray);
  85453. var hit = ray.intersectsMesh(impostor.object);
  85454. var contactPoint = hit.pickedPoint;
  85455. if (!contactPoint) {
  85456. return null;
  85457. }
  85458. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85459. if (distanceFromOrigin > radius) {
  85460. return null;
  85461. }
  85462. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85463. ? strength
  85464. : strength * (1 - (distanceFromOrigin / radius));
  85465. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85466. return { force: force, contactPoint: contactPoint };
  85467. };
  85468. /**
  85469. * Disposes the sphere.
  85470. * @param {bolean} force
  85471. */
  85472. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85473. var _this = this;
  85474. if (force === void 0) { force = true; }
  85475. if (force) {
  85476. this._sphere.dispose();
  85477. }
  85478. else {
  85479. setTimeout(function () {
  85480. if (!_this._dataFetched) {
  85481. _this._sphere.dispose();
  85482. }
  85483. }, 0);
  85484. }
  85485. };
  85486. /*** Helpers ***/
  85487. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85488. if (!this._sphere) {
  85489. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85490. this._sphere.isVisible = false;
  85491. }
  85492. };
  85493. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85494. var impostorObject = impostor.object;
  85495. this._prepareSphere();
  85496. this._sphere.position = origin;
  85497. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85498. this._sphere._updateBoundingInfo();
  85499. this._sphere.computeWorldMatrix(true);
  85500. return this._sphere.intersectsMesh(impostorObject, true);
  85501. };
  85502. return PhysicsRadialExplosionEvent;
  85503. }());
  85504. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85505. /***** Gravitational Field *****/
  85506. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85507. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85508. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85509. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85510. this._physicsHelper = physicsHelper;
  85511. this._scene = scene;
  85512. this._origin = origin;
  85513. this._radius = radius;
  85514. this._strength = strength;
  85515. this._falloff = falloff;
  85516. this._tickCallback = this._tick.bind(this);
  85517. }
  85518. /**
  85519. * Returns the data related to the gravitational field event (sphere).
  85520. * @returns {PhysicsGravitationalFieldEventData}
  85521. */
  85522. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85523. this._dataFetched = true;
  85524. return {
  85525. sphere: this._sphere,
  85526. };
  85527. };
  85528. /**
  85529. * Enables the gravitational field.
  85530. */
  85531. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85532. this._tickCallback.call(this);
  85533. this._scene.registerBeforeRender(this._tickCallback);
  85534. };
  85535. /**
  85536. * Disables the gravitational field.
  85537. */
  85538. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85539. this._scene.unregisterBeforeRender(this._tickCallback);
  85540. };
  85541. /**
  85542. * Disposes the sphere.
  85543. * @param {bolean} force
  85544. */
  85545. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85546. var _this = this;
  85547. if (force === void 0) { force = true; }
  85548. if (force) {
  85549. this._sphere.dispose();
  85550. }
  85551. else {
  85552. setTimeout(function () {
  85553. if (!_this._dataFetched) {
  85554. _this._sphere.dispose();
  85555. }
  85556. }, 0);
  85557. }
  85558. };
  85559. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85560. // Since the params won't change, we fetch the event only once
  85561. if (this._sphere) {
  85562. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85563. }
  85564. else {
  85565. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85566. if (radialExplosionEvent) {
  85567. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85568. }
  85569. }
  85570. };
  85571. return PhysicsGravitationalFieldEvent;
  85572. }());
  85573. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85574. /***** Updraft *****/
  85575. var PhysicsUpdraftEvent = /** @class */ (function () {
  85576. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85577. this._scene = _scene;
  85578. this._origin = _origin;
  85579. this._radius = _radius;
  85580. this._strength = _strength;
  85581. this._height = _height;
  85582. this._updraftMode = _updraftMode;
  85583. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85584. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85585. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85586. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85587. this._physicsEngine = this._scene.getPhysicsEngine();
  85588. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85589. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85590. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85591. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85592. }
  85593. this._tickCallback = this._tick.bind(this);
  85594. }
  85595. /**
  85596. * Returns the data related to the updraft event (cylinder).
  85597. * @returns {PhysicsUpdraftEventData}
  85598. */
  85599. PhysicsUpdraftEvent.prototype.getData = function () {
  85600. this._dataFetched = true;
  85601. return {
  85602. cylinder: this._cylinder,
  85603. };
  85604. };
  85605. /**
  85606. * Enables the updraft.
  85607. */
  85608. PhysicsUpdraftEvent.prototype.enable = function () {
  85609. this._tickCallback.call(this);
  85610. this._scene.registerBeforeRender(this._tickCallback);
  85611. };
  85612. /**
  85613. * Disables the cortex.
  85614. */
  85615. PhysicsUpdraftEvent.prototype.disable = function () {
  85616. this._scene.unregisterBeforeRender(this._tickCallback);
  85617. };
  85618. /**
  85619. * Disposes the sphere.
  85620. * @param {bolean} force
  85621. */
  85622. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85623. var _this = this;
  85624. if (force === void 0) { force = true; }
  85625. if (force) {
  85626. this._cylinder.dispose();
  85627. }
  85628. else {
  85629. setTimeout(function () {
  85630. if (!_this._dataFetched) {
  85631. _this._cylinder.dispose();
  85632. }
  85633. }, 0);
  85634. }
  85635. };
  85636. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85637. if (impostor.mass === 0) {
  85638. return null;
  85639. }
  85640. if (!this._intersectsWithCylinder(impostor)) {
  85641. return null;
  85642. }
  85643. var impostorObjectCenter = impostor.getObjectCenter();
  85644. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85645. var direction = this._originDirection;
  85646. }
  85647. else {
  85648. var direction = impostorObjectCenter.subtract(this._originTop);
  85649. }
  85650. var multiplier = this._strength * -1;
  85651. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85652. return { force: force, contactPoint: impostorObjectCenter };
  85653. };
  85654. PhysicsUpdraftEvent.prototype._tick = function () {
  85655. var _this = this;
  85656. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85657. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85658. if (!impostorForceAndContactPoint) {
  85659. return;
  85660. }
  85661. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85662. });
  85663. };
  85664. /*** Helpers ***/
  85665. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85666. if (!this._cylinder) {
  85667. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85668. height: this._height,
  85669. diameter: this._radius * 2,
  85670. }, this._scene);
  85671. this._cylinder.isVisible = false;
  85672. }
  85673. };
  85674. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85675. var impostorObject = impostor.object;
  85676. this._prepareCylinder();
  85677. this._cylinder.position = this._cylinderPosition;
  85678. return this._cylinder.intersectsMesh(impostorObject, true);
  85679. };
  85680. return PhysicsUpdraftEvent;
  85681. }());
  85682. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85683. /***** Vortex *****/
  85684. var PhysicsVortexEvent = /** @class */ (function () {
  85685. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85686. this._scene = _scene;
  85687. this._origin = _origin;
  85688. this._radius = _radius;
  85689. this._strength = _strength;
  85690. this._height = _height;
  85691. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85692. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85693. this._updraftMultiplier = 0.02;
  85694. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85695. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85696. this._physicsEngine = this._scene.getPhysicsEngine();
  85697. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85698. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85699. this._tickCallback = this._tick.bind(this);
  85700. }
  85701. /**
  85702. * Returns the data related to the vortex event (cylinder).
  85703. * @returns {PhysicsVortexEventData}
  85704. */
  85705. PhysicsVortexEvent.prototype.getData = function () {
  85706. this._dataFetched = true;
  85707. return {
  85708. cylinder: this._cylinder,
  85709. };
  85710. };
  85711. /**
  85712. * Enables the vortex.
  85713. */
  85714. PhysicsVortexEvent.prototype.enable = function () {
  85715. this._tickCallback.call(this);
  85716. this._scene.registerBeforeRender(this._tickCallback);
  85717. };
  85718. /**
  85719. * Disables the cortex.
  85720. */
  85721. PhysicsVortexEvent.prototype.disable = function () {
  85722. this._scene.unregisterBeforeRender(this._tickCallback);
  85723. };
  85724. /**
  85725. * Disposes the sphere.
  85726. * @param {bolean} force
  85727. */
  85728. PhysicsVortexEvent.prototype.dispose = function (force) {
  85729. var _this = this;
  85730. if (force === void 0) { force = true; }
  85731. if (force) {
  85732. this._cylinder.dispose();
  85733. }
  85734. else {
  85735. setTimeout(function () {
  85736. if (!_this._dataFetched) {
  85737. _this._cylinder.dispose();
  85738. }
  85739. }, 0);
  85740. }
  85741. };
  85742. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85743. if (impostor.mass === 0) {
  85744. return null;
  85745. }
  85746. if (!this._intersectsWithCylinder(impostor)) {
  85747. return null;
  85748. }
  85749. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85750. return null;
  85751. }
  85752. var impostorObjectCenter = impostor.getObjectCenter();
  85753. 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)
  85754. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85755. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85756. var hit = ray.intersectsMesh(impostor.object);
  85757. var contactPoint = hit.pickedPoint;
  85758. if (!contactPoint) {
  85759. return null;
  85760. }
  85761. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85762. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85763. var directionToOrigin = contactPoint.normalize();
  85764. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85765. directionToOrigin = directionToOrigin.negate();
  85766. }
  85767. // TODO: find a more physically based solution
  85768. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85769. var forceX = directionToOrigin.x * this._strength / 8;
  85770. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85771. var forceZ = directionToOrigin.z * this._strength / 8;
  85772. }
  85773. else {
  85774. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85775. var forceY = this._originTop.y * this._updraftMultiplier;
  85776. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85777. }
  85778. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85779. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85780. return { force: force, contactPoint: impostorObjectCenter };
  85781. };
  85782. PhysicsVortexEvent.prototype._tick = function () {
  85783. var _this = this;
  85784. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85785. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85786. if (!impostorForceAndContactPoint) {
  85787. return;
  85788. }
  85789. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85790. });
  85791. };
  85792. /*** Helpers ***/
  85793. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85794. if (!this._cylinder) {
  85795. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85796. height: this._height,
  85797. diameter: this._radius * 2,
  85798. }, this._scene);
  85799. this._cylinder.isVisible = false;
  85800. }
  85801. };
  85802. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85803. var impostorObject = impostor.object;
  85804. this._prepareCylinder();
  85805. this._cylinder.position = this._cylinderPosition;
  85806. return this._cylinder.intersectsMesh(impostorObject, true);
  85807. };
  85808. return PhysicsVortexEvent;
  85809. }());
  85810. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85811. /***** Enums *****/
  85812. /**
  85813. * The strenght of the force in correspondence to the distance of the affected object
  85814. */
  85815. var PhysicsRadialImpulseFalloff;
  85816. (function (PhysicsRadialImpulseFalloff) {
  85817. /** Defines that impulse is constant in strength across it's whole radius */
  85818. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85819. /** DEfines that impulse gets weaker if it's further from the origin */
  85820. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85821. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85822. /**
  85823. * The strenght of the force in correspondence to the distance of the affected object
  85824. */
  85825. var PhysicsUpdraftMode;
  85826. (function (PhysicsUpdraftMode) {
  85827. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85828. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85829. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85830. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85831. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85832. })(BABYLON || (BABYLON = {}));
  85833. //# sourceMappingURL=babylon.physicsHelper.js.map
  85834. var BABYLON;
  85835. (function (BABYLON) {
  85836. var CannonJSPlugin = /** @class */ (function () {
  85837. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85838. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85839. if (iterations === void 0) { iterations = 10; }
  85840. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85841. this.name = "CannonJSPlugin";
  85842. this._physicsMaterials = new Array();
  85843. this._fixedTimeStep = 1 / 60;
  85844. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85845. this.BJSCANNON = CANNON;
  85846. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85847. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85848. this._tmpPosition = BABYLON.Vector3.Zero();
  85849. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85850. this._tmpUnityRotation = new BABYLON.Quaternion();
  85851. if (!this.isSupported()) {
  85852. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85853. return;
  85854. }
  85855. this._extendNamespace();
  85856. this.world = new this.BJSCANNON.World();
  85857. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85858. this.world.solver.iterations = iterations;
  85859. }
  85860. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85861. this.world.gravity.copy(gravity);
  85862. };
  85863. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85864. this._fixedTimeStep = timeStep;
  85865. };
  85866. CannonJSPlugin.prototype.getTimeStep = function () {
  85867. return this._fixedTimeStep;
  85868. };
  85869. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85870. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85871. };
  85872. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85873. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85874. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85875. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85876. };
  85877. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85878. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85879. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85880. impostor.physicsBody.applyForce(impulse, worldPoint);
  85881. };
  85882. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85883. //parent-child relationship. Does this impostor has a parent impostor?
  85884. if (impostor.parent) {
  85885. if (impostor.physicsBody) {
  85886. this.removePhysicsBody(impostor);
  85887. //TODO is that needed?
  85888. impostor.forceUpdate();
  85889. }
  85890. return;
  85891. }
  85892. //should a new body be created for this impostor?
  85893. if (impostor.isBodyInitRequired()) {
  85894. var shape = this._createShape(impostor);
  85895. //unregister events, if body is being changed
  85896. var oldBody = impostor.physicsBody;
  85897. if (oldBody) {
  85898. this.removePhysicsBody(impostor);
  85899. }
  85900. //create the body and material
  85901. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85902. var bodyCreationObject = {
  85903. mass: impostor.getParam("mass"),
  85904. material: material
  85905. };
  85906. // A simple extend, in case native options were used.
  85907. var nativeOptions = impostor.getParam("nativeOptions");
  85908. for (var key in nativeOptions) {
  85909. if (nativeOptions.hasOwnProperty(key)) {
  85910. bodyCreationObject[key] = nativeOptions[key];
  85911. }
  85912. }
  85913. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85914. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85915. this.world.addEventListener("preStep", impostor.beforeStep);
  85916. this.world.addEventListener("postStep", impostor.afterStep);
  85917. impostor.physicsBody.addShape(shape);
  85918. this.world.add(impostor.physicsBody);
  85919. //try to keep the body moving in the right direction by taking old properties.
  85920. //Should be tested!
  85921. if (oldBody) {
  85922. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85923. impostor.physicsBody[param].copy(oldBody[param]);
  85924. });
  85925. }
  85926. this._processChildMeshes(impostor);
  85927. }
  85928. //now update the body's transformation
  85929. this._updatePhysicsBodyTransformation(impostor);
  85930. };
  85931. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85932. var _this = this;
  85933. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85934. var currentRotation = mainImpostor.object.rotationQuaternion;
  85935. if (meshChildren.length) {
  85936. var processMesh = function (localPosition, mesh) {
  85937. if (!currentRotation || !mesh.rotationQuaternion) {
  85938. return;
  85939. }
  85940. var childImpostor = mesh.getPhysicsImpostor();
  85941. if (childImpostor) {
  85942. var parent = childImpostor.parent;
  85943. if (parent !== mainImpostor) {
  85944. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85945. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85946. if (childImpostor.physicsBody) {
  85947. _this.removePhysicsBody(childImpostor);
  85948. childImpostor.physicsBody = null;
  85949. }
  85950. childImpostor.parent = mainImpostor;
  85951. childImpostor.resetUpdateFlags();
  85952. 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));
  85953. //Add the mass of the children.
  85954. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85955. }
  85956. }
  85957. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85958. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85959. };
  85960. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85961. }
  85962. };
  85963. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85964. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85965. this.world.removeEventListener("preStep", impostor.beforeStep);
  85966. this.world.removeEventListener("postStep", impostor.afterStep);
  85967. this.world.remove(impostor.physicsBody);
  85968. };
  85969. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85970. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85971. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85972. if (!mainBody || !connectedBody) {
  85973. return;
  85974. }
  85975. var constraint;
  85976. var jointData = impostorJoint.joint.jointData;
  85977. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85978. var constraintData = {
  85979. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85980. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85981. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85982. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85983. maxForce: jointData.nativeParams.maxForce,
  85984. collideConnected: !!jointData.collision
  85985. };
  85986. switch (impostorJoint.joint.type) {
  85987. case BABYLON.PhysicsJoint.HingeJoint:
  85988. case BABYLON.PhysicsJoint.Hinge2Joint:
  85989. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85990. break;
  85991. case BABYLON.PhysicsJoint.DistanceJoint:
  85992. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85993. break;
  85994. case BABYLON.PhysicsJoint.SpringJoint:
  85995. var springData = jointData;
  85996. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85997. restLength: springData.length,
  85998. stiffness: springData.stiffness,
  85999. damping: springData.damping,
  86000. localAnchorA: constraintData.pivotA,
  86001. localAnchorB: constraintData.pivotB
  86002. });
  86003. break;
  86004. case BABYLON.PhysicsJoint.LockJoint:
  86005. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86006. break;
  86007. case BABYLON.PhysicsJoint.PointToPointJoint:
  86008. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86009. default:
  86010. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86011. break;
  86012. }
  86013. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86014. constraint.collideConnected = !!jointData.collision;
  86015. impostorJoint.joint.physicsJoint = constraint;
  86016. //don't add spring as constraint, as it is not one.
  86017. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86018. this.world.addConstraint(constraint);
  86019. }
  86020. else {
  86021. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86022. constraint.applyForce();
  86023. });
  86024. }
  86025. };
  86026. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86027. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86028. };
  86029. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86030. var index;
  86031. var mat;
  86032. for (index = 0; index < this._physicsMaterials.length; index++) {
  86033. mat = this._physicsMaterials[index];
  86034. if (mat.friction === friction && mat.restitution === restitution) {
  86035. return mat;
  86036. }
  86037. }
  86038. var currentMat = new this.BJSCANNON.Material(name);
  86039. currentMat.friction = friction;
  86040. currentMat.restitution = restitution;
  86041. this._physicsMaterials.push(currentMat);
  86042. return currentMat;
  86043. };
  86044. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86045. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86046. };
  86047. CannonJSPlugin.prototype._createShape = function (impostor) {
  86048. var object = impostor.object;
  86049. var returnValue;
  86050. var extendSize = impostor.getObjectExtendSize();
  86051. switch (impostor.type) {
  86052. case BABYLON.PhysicsImpostor.SphereImpostor:
  86053. var radiusX = extendSize.x;
  86054. var radiusY = extendSize.y;
  86055. var radiusZ = extendSize.z;
  86056. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86057. break;
  86058. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86059. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86060. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86061. break;
  86062. case BABYLON.PhysicsImpostor.BoxImpostor:
  86063. var box = extendSize.scale(0.5);
  86064. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86065. break;
  86066. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86067. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86068. returnValue = new this.BJSCANNON.Plane();
  86069. break;
  86070. case BABYLON.PhysicsImpostor.MeshImpostor:
  86071. // should transform the vertex data to world coordinates!!
  86072. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86073. var rawFaces = object.getIndices ? object.getIndices() : [];
  86074. if (!rawVerts)
  86075. return;
  86076. // get only scale! so the object could transform correctly.
  86077. var oldPosition = object.position.clone();
  86078. var oldRotation = object.rotation && object.rotation.clone();
  86079. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86080. object.position.copyFromFloats(0, 0, 0);
  86081. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86082. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86083. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86084. var transform = object.computeWorldMatrix(true);
  86085. // convert rawVerts to object space
  86086. var temp = new Array();
  86087. var index;
  86088. for (index = 0; index < rawVerts.length; index += 3) {
  86089. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86090. }
  86091. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86092. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86093. //now set back the transformation!
  86094. object.position.copyFrom(oldPosition);
  86095. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86096. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86097. break;
  86098. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86099. var oldPosition2 = object.position.clone();
  86100. var oldRotation2 = object.rotation && object.rotation.clone();
  86101. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86102. object.position.copyFromFloats(0, 0, 0);
  86103. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86104. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86105. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86106. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86107. returnValue = this._createHeightmap(object);
  86108. object.position.copyFrom(oldPosition2);
  86109. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86110. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86111. object.computeWorldMatrix(true);
  86112. break;
  86113. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86114. returnValue = new this.BJSCANNON.Particle();
  86115. break;
  86116. }
  86117. return returnValue;
  86118. };
  86119. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86120. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86121. var transform = object.computeWorldMatrix(true);
  86122. // convert rawVerts to object space
  86123. var temp = new Array();
  86124. var index;
  86125. for (index = 0; index < pos.length; index += 3) {
  86126. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86127. }
  86128. pos = temp;
  86129. var matrix = new Array();
  86130. //For now pointDepth will not be used and will be automatically calculated.
  86131. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86132. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86133. var boundingInfo = object.getBoundingInfo();
  86134. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86135. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86136. var elementSize = dim * 2 / arraySize;
  86137. for (var i = 0; i < pos.length; i = i + 3) {
  86138. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86139. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86140. var y = -pos[i + 2] + minY;
  86141. if (!matrix[x]) {
  86142. matrix[x] = [];
  86143. }
  86144. if (!matrix[x][z]) {
  86145. matrix[x][z] = y;
  86146. }
  86147. matrix[x][z] = Math.max(y, matrix[x][z]);
  86148. }
  86149. for (var x = 0; x <= arraySize; ++x) {
  86150. if (!matrix[x]) {
  86151. var loc = 1;
  86152. while (!matrix[(x + loc) % arraySize]) {
  86153. loc++;
  86154. }
  86155. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86156. //console.log("missing x", x);
  86157. }
  86158. for (var z = 0; z <= arraySize; ++z) {
  86159. if (!matrix[x][z]) {
  86160. var loc = 1;
  86161. var newValue;
  86162. while (newValue === undefined) {
  86163. newValue = matrix[x][(z + loc++) % arraySize];
  86164. }
  86165. matrix[x][z] = newValue;
  86166. }
  86167. }
  86168. }
  86169. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86170. elementSize: elementSize
  86171. });
  86172. //For future reference, needed for body transformation
  86173. shape.minY = minY;
  86174. return shape;
  86175. };
  86176. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86177. var object = impostor.object;
  86178. //make sure it is updated...
  86179. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86180. // The delta between the mesh position and the mesh bounding box center
  86181. var bInfo = object.getBoundingInfo();
  86182. if (!bInfo)
  86183. return;
  86184. var center = impostor.getObjectCenter();
  86185. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86186. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86187. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86188. this._tmpPosition.copyFrom(center);
  86189. var quaternion = object.rotationQuaternion;
  86190. if (!quaternion) {
  86191. return;
  86192. }
  86193. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86194. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86195. //-90 DEG in X, precalculated
  86196. quaternion = quaternion.multiply(this._minus90X);
  86197. //Invert! (Precalculated, 90 deg in X)
  86198. //No need to clone. this will never change.
  86199. impostor.setDeltaRotation(this._plus90X);
  86200. }
  86201. //If it is a heightfield, if should be centered.
  86202. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86203. var mesh = object;
  86204. var boundingInfo = mesh.getBoundingInfo();
  86205. //calculate the correct body position:
  86206. var rotationQuaternion = mesh.rotationQuaternion;
  86207. mesh.rotationQuaternion = this._tmpUnityRotation;
  86208. mesh.computeWorldMatrix(true);
  86209. //get original center with no rotation
  86210. var c = center.clone();
  86211. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86212. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86213. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86214. mesh.setPreTransformMatrix(p);
  86215. mesh.computeWorldMatrix(true);
  86216. //calculate the translation
  86217. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86218. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86219. //add it inverted to the delta
  86220. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86221. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86222. //rotation is back
  86223. mesh.rotationQuaternion = rotationQuaternion;
  86224. mesh.setPreTransformMatrix(oldPivot);
  86225. mesh.computeWorldMatrix(true);
  86226. }
  86227. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86228. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86229. //this._tmpPosition.copyFrom(object.position);
  86230. }
  86231. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86232. //Now update the impostor object
  86233. impostor.physicsBody.position.copy(this._tmpPosition);
  86234. impostor.physicsBody.quaternion.copy(quaternion);
  86235. };
  86236. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86237. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86238. if (impostor.object.rotationQuaternion) {
  86239. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86240. }
  86241. };
  86242. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86243. impostor.physicsBody.position.copy(newPosition);
  86244. impostor.physicsBody.quaternion.copy(newRotation);
  86245. };
  86246. CannonJSPlugin.prototype.isSupported = function () {
  86247. return this.BJSCANNON !== undefined;
  86248. };
  86249. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86250. impostor.physicsBody.velocity.copy(velocity);
  86251. };
  86252. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86253. impostor.physicsBody.angularVelocity.copy(velocity);
  86254. };
  86255. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86256. var v = impostor.physicsBody.velocity;
  86257. if (!v) {
  86258. return null;
  86259. }
  86260. return new BABYLON.Vector3(v.x, v.y, v.z);
  86261. };
  86262. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86263. var v = impostor.physicsBody.angularVelocity;
  86264. if (!v) {
  86265. return null;
  86266. }
  86267. return new BABYLON.Vector3(v.x, v.y, v.z);
  86268. };
  86269. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86270. impostor.physicsBody.mass = mass;
  86271. impostor.physicsBody.updateMassProperties();
  86272. };
  86273. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86274. return impostor.physicsBody.mass;
  86275. };
  86276. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86277. return impostor.physicsBody.material.friction;
  86278. };
  86279. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86280. impostor.physicsBody.material.friction = friction;
  86281. };
  86282. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86283. return impostor.physicsBody.material.restitution;
  86284. };
  86285. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86286. impostor.physicsBody.material.restitution = restitution;
  86287. };
  86288. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86289. impostor.physicsBody.sleep();
  86290. };
  86291. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86292. impostor.physicsBody.wakeUp();
  86293. };
  86294. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86295. joint.physicsJoint.distance = maxDistance;
  86296. };
  86297. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86298. // if (!motorIndex) {
  86299. // joint.physicsJoint.enableMotor();
  86300. // }
  86301. // }
  86302. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86303. // if (!motorIndex) {
  86304. // joint.physicsJoint.disableMotor();
  86305. // }
  86306. // }
  86307. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86308. if (!motorIndex) {
  86309. joint.physicsJoint.enableMotor();
  86310. joint.physicsJoint.setMotorSpeed(speed);
  86311. if (maxForce) {
  86312. this.setLimit(joint, maxForce);
  86313. }
  86314. }
  86315. };
  86316. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86317. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86318. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86319. };
  86320. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86321. var body = impostor.physicsBody;
  86322. mesh.position.x = body.position.x;
  86323. mesh.position.y = body.position.y;
  86324. mesh.position.z = body.position.z;
  86325. if (mesh.rotationQuaternion) {
  86326. mesh.rotationQuaternion.x = body.quaternion.x;
  86327. mesh.rotationQuaternion.y = body.quaternion.y;
  86328. mesh.rotationQuaternion.z = body.quaternion.z;
  86329. mesh.rotationQuaternion.w = body.quaternion.w;
  86330. }
  86331. };
  86332. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86333. var shape = impostor.physicsBody.shapes[0];
  86334. return shape.boundingSphereRadius;
  86335. };
  86336. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86337. var shape = impostor.physicsBody.shapes[0];
  86338. result.x = shape.halfExtents.x * 2;
  86339. result.y = shape.halfExtents.y * 2;
  86340. result.z = shape.halfExtents.z * 2;
  86341. };
  86342. CannonJSPlugin.prototype.dispose = function () {
  86343. };
  86344. CannonJSPlugin.prototype._extendNamespace = function () {
  86345. //this will force cannon to execute at least one step when using interpolation
  86346. var step_tmp1 = new this.BJSCANNON.Vec3();
  86347. var Engine = this.BJSCANNON;
  86348. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86349. maxSubSteps = maxSubSteps || 10;
  86350. timeSinceLastCalled = timeSinceLastCalled || 0;
  86351. if (timeSinceLastCalled === 0) {
  86352. this.internalStep(dt);
  86353. this.time += dt;
  86354. }
  86355. else {
  86356. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86357. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86358. var t0 = performance.now();
  86359. for (var i = 0; i !== internalSteps; i++) {
  86360. this.internalStep(dt);
  86361. if (performance.now() - t0 > dt * 1000) {
  86362. break;
  86363. }
  86364. }
  86365. this.time += timeSinceLastCalled;
  86366. var h = this.time % dt;
  86367. var h_div_dt = h / dt;
  86368. var interpvelo = step_tmp1;
  86369. var bodies = this.bodies;
  86370. for (var j = 0; j !== bodies.length; j++) {
  86371. var b = bodies[j];
  86372. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86373. b.position.vsub(b.previousPosition, interpvelo);
  86374. interpvelo.scale(h_div_dt, interpvelo);
  86375. b.position.vadd(interpvelo, b.interpolatedPosition);
  86376. }
  86377. else {
  86378. b.interpolatedPosition.copy(b.position);
  86379. b.interpolatedQuaternion.copy(b.quaternion);
  86380. }
  86381. }
  86382. }
  86383. };
  86384. };
  86385. return CannonJSPlugin;
  86386. }());
  86387. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86388. })(BABYLON || (BABYLON = {}));
  86389. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86390. var BABYLON;
  86391. (function (BABYLON) {
  86392. var OimoJSPlugin = /** @class */ (function () {
  86393. function OimoJSPlugin(iterations) {
  86394. this.name = "OimoJSPlugin";
  86395. this._tmpImpostorsArray = [];
  86396. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86397. this.BJSOIMO = OIMO;
  86398. this.world = new this.BJSOIMO.World({
  86399. iterations: iterations
  86400. });
  86401. this.world.clear();
  86402. }
  86403. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86404. this.world.gravity.copy(gravity);
  86405. };
  86406. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86407. this.world.timeStep = timeStep;
  86408. };
  86409. OimoJSPlugin.prototype.getTimeStep = function () {
  86410. return this.world.timeStep;
  86411. };
  86412. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86413. var _this = this;
  86414. impostors.forEach(function (impostor) {
  86415. impostor.beforeStep();
  86416. });
  86417. this.world.step();
  86418. impostors.forEach(function (impostor) {
  86419. impostor.afterStep();
  86420. //update the ordered impostors array
  86421. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86422. });
  86423. //check for collisions
  86424. var contact = this.world.contacts;
  86425. while (contact !== null) {
  86426. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86427. contact = contact.next;
  86428. continue;
  86429. }
  86430. //is this body colliding with any other? get the impostor
  86431. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86432. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86433. if (!mainImpostor || !collidingImpostor) {
  86434. contact = contact.next;
  86435. continue;
  86436. }
  86437. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86438. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86439. contact = contact.next;
  86440. }
  86441. };
  86442. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86443. var mass = impostor.physicsBody.mass;
  86444. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86445. };
  86446. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86447. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86448. this.applyImpulse(impostor, force, contactPoint);
  86449. };
  86450. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86451. var _this = this;
  86452. //parent-child relationship. Does this impostor has a parent impostor?
  86453. if (impostor.parent) {
  86454. if (impostor.physicsBody) {
  86455. this.removePhysicsBody(impostor);
  86456. //TODO is that needed?
  86457. impostor.forceUpdate();
  86458. }
  86459. return;
  86460. }
  86461. if (impostor.isBodyInitRequired()) {
  86462. var bodyConfig = {
  86463. name: impostor.uniqueId,
  86464. //Oimo must have mass, also for static objects.
  86465. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86466. size: [],
  86467. type: [],
  86468. pos: [],
  86469. posShape: [],
  86470. rot: [],
  86471. rotShape: [],
  86472. move: impostor.getParam("mass") !== 0,
  86473. density: impostor.getParam("mass"),
  86474. friction: impostor.getParam("friction"),
  86475. restitution: impostor.getParam("restitution"),
  86476. //Supporting older versions of Oimo
  86477. world: this.world
  86478. };
  86479. var impostors = [impostor];
  86480. var addToArray = function (parent) {
  86481. if (!parent.getChildMeshes)
  86482. return;
  86483. parent.getChildMeshes().forEach(function (m) {
  86484. if (m.physicsImpostor) {
  86485. impostors.push(m.physicsImpostor);
  86486. //m.physicsImpostor._init();
  86487. }
  86488. });
  86489. };
  86490. addToArray(impostor.object);
  86491. var checkWithEpsilon_1 = function (value) {
  86492. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86493. };
  86494. impostors.forEach(function (i) {
  86495. if (!i.object.rotationQuaternion) {
  86496. return;
  86497. }
  86498. //get the correct bounding box
  86499. var oldQuaternion = i.object.rotationQuaternion;
  86500. var rot = oldQuaternion.toEulerAngles();
  86501. var extendSize = i.getObjectExtendSize();
  86502. var radToDeg = 57.295779513082320876;
  86503. if (i === impostor) {
  86504. var center = impostor.getObjectCenter();
  86505. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86506. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86507. //Can also use Array.prototype.push.apply
  86508. bodyConfig.pos.push(center.x);
  86509. bodyConfig.pos.push(center.y);
  86510. bodyConfig.pos.push(center.z);
  86511. bodyConfig.posShape.push(0, 0, 0);
  86512. //tmp solution
  86513. bodyConfig.rot.push(rot.x * radToDeg);
  86514. bodyConfig.rot.push(rot.y * radToDeg);
  86515. bodyConfig.rot.push(rot.z * radToDeg);
  86516. bodyConfig.rotShape.push(0, 0, 0);
  86517. }
  86518. else {
  86519. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86520. bodyConfig.posShape.push(localPosition.x);
  86521. bodyConfig.posShape.push(localPosition.y);
  86522. bodyConfig.posShape.push(localPosition.z);
  86523. bodyConfig.pos.push(0, 0, 0);
  86524. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86525. bodyConfig.rot.push(0);
  86526. bodyConfig.rot.push(0);
  86527. bodyConfig.rot.push(0);
  86528. bodyConfig.rotShape.push(rot.x * radToDeg);
  86529. bodyConfig.rotShape.push(rot.y * radToDeg);
  86530. bodyConfig.rotShape.push(rot.z * radToDeg);
  86531. }
  86532. // register mesh
  86533. switch (i.type) {
  86534. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86535. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86536. case BABYLON.PhysicsImpostor.SphereImpostor:
  86537. var radiusX = extendSize.x;
  86538. var radiusY = extendSize.y;
  86539. var radiusZ = extendSize.z;
  86540. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86541. bodyConfig.type.push('sphere');
  86542. //due to the way oimo works with compounds, add 3 times
  86543. bodyConfig.size.push(size);
  86544. bodyConfig.size.push(size);
  86545. bodyConfig.size.push(size);
  86546. break;
  86547. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86548. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86549. var sizeY = checkWithEpsilon_1(extendSize.y);
  86550. bodyConfig.type.push('cylinder');
  86551. bodyConfig.size.push(sizeX);
  86552. bodyConfig.size.push(sizeY);
  86553. //due to the way oimo works with compounds, add one more value.
  86554. bodyConfig.size.push(sizeY);
  86555. break;
  86556. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86557. case BABYLON.PhysicsImpostor.BoxImpostor:
  86558. default:
  86559. var sizeX = checkWithEpsilon_1(extendSize.x);
  86560. var sizeY = checkWithEpsilon_1(extendSize.y);
  86561. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86562. bodyConfig.type.push('box');
  86563. //if (i === impostor) {
  86564. bodyConfig.size.push(sizeX);
  86565. bodyConfig.size.push(sizeY);
  86566. bodyConfig.size.push(sizeZ);
  86567. //} else {
  86568. // bodyConfig.size.push(0,0,0);
  86569. //}
  86570. break;
  86571. }
  86572. //actually not needed, but hey...
  86573. i.object.rotationQuaternion = oldQuaternion;
  86574. });
  86575. impostor.physicsBody = this.world.add(bodyConfig);
  86576. }
  86577. else {
  86578. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86579. }
  86580. impostor.setDeltaPosition(this._tmpPositionVector);
  86581. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86582. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86583. };
  86584. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86585. //impostor.physicsBody.dispose();
  86586. //Same as : (older oimo versions)
  86587. this.world.removeRigidBody(impostor.physicsBody);
  86588. };
  86589. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86590. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86591. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86592. if (!mainBody || !connectedBody) {
  86593. return;
  86594. }
  86595. var jointData = impostorJoint.joint.jointData;
  86596. var options = jointData.nativeParams || {};
  86597. var type;
  86598. var nativeJointData = {
  86599. body1: mainBody,
  86600. body2: connectedBody,
  86601. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86602. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86603. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86604. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86605. min: options.min,
  86606. max: options.max,
  86607. collision: options.collision || jointData.collision,
  86608. spring: options.spring,
  86609. //supporting older version of Oimo
  86610. world: this.world
  86611. };
  86612. switch (impostorJoint.joint.type) {
  86613. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86614. type = "jointBall";
  86615. break;
  86616. case BABYLON.PhysicsJoint.SpringJoint:
  86617. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86618. var springData = jointData;
  86619. nativeJointData.min = springData.length || nativeJointData.min;
  86620. //Max should also be set, just make sure it is at least min
  86621. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86622. case BABYLON.PhysicsJoint.DistanceJoint:
  86623. type = "jointDistance";
  86624. nativeJointData.max = jointData.maxDistance;
  86625. break;
  86626. case BABYLON.PhysicsJoint.PrismaticJoint:
  86627. type = "jointPrisme";
  86628. break;
  86629. case BABYLON.PhysicsJoint.SliderJoint:
  86630. type = "jointSlide";
  86631. break;
  86632. case BABYLON.PhysicsJoint.WheelJoint:
  86633. type = "jointWheel";
  86634. break;
  86635. case BABYLON.PhysicsJoint.HingeJoint:
  86636. default:
  86637. type = "jointHinge";
  86638. break;
  86639. }
  86640. nativeJointData.type = type;
  86641. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86642. };
  86643. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86644. //Bug in Oimo prevents us from disposing a joint in the playground
  86645. //joint.joint.physicsJoint.dispose();
  86646. //So we will bruteforce it!
  86647. try {
  86648. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86649. }
  86650. catch (e) {
  86651. BABYLON.Tools.Warn(e);
  86652. }
  86653. };
  86654. OimoJSPlugin.prototype.isSupported = function () {
  86655. return this.BJSOIMO !== undefined;
  86656. };
  86657. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86658. if (!impostor.physicsBody.sleeping) {
  86659. //TODO check that
  86660. /*if (impostor.physicsBody.shapes.next) {
  86661. var parentShape = this._getLastShape(impostor.physicsBody);
  86662. impostor.object.position.copyFrom(parentShape.position);
  86663. console.log(parentShape.position);
  86664. } else {*/
  86665. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86666. //}
  86667. if (impostor.object.rotationQuaternion) {
  86668. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86669. }
  86670. }
  86671. };
  86672. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86673. var body = impostor.physicsBody;
  86674. body.position.copy(newPosition);
  86675. body.orientation.copy(newRotation);
  86676. body.syncShapes();
  86677. body.awake();
  86678. };
  86679. /*private _getLastShape(body: any): any {
  86680. var lastShape = body.shapes;
  86681. while (lastShape.next) {
  86682. lastShape = lastShape.next;
  86683. }
  86684. return lastShape;
  86685. }*/
  86686. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86687. impostor.physicsBody.linearVelocity.copy(velocity);
  86688. };
  86689. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86690. impostor.physicsBody.angularVelocity.copy(velocity);
  86691. };
  86692. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86693. var v = impostor.physicsBody.linearVelocity;
  86694. if (!v) {
  86695. return null;
  86696. }
  86697. return new BABYLON.Vector3(v.x, v.y, v.z);
  86698. };
  86699. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86700. var v = impostor.physicsBody.angularVelocity;
  86701. if (!v) {
  86702. return null;
  86703. }
  86704. return new BABYLON.Vector3(v.x, v.y, v.z);
  86705. };
  86706. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86707. var staticBody = mass === 0;
  86708. //this will actually set the body's density and not its mass.
  86709. //But this is how oimo treats the mass variable.
  86710. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86711. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86712. };
  86713. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86714. return impostor.physicsBody.shapes.density;
  86715. };
  86716. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86717. return impostor.physicsBody.shapes.friction;
  86718. };
  86719. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86720. impostor.physicsBody.shapes.friction = friction;
  86721. };
  86722. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86723. return impostor.physicsBody.shapes.restitution;
  86724. };
  86725. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86726. impostor.physicsBody.shapes.restitution = restitution;
  86727. };
  86728. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86729. impostor.physicsBody.sleep();
  86730. };
  86731. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86732. impostor.physicsBody.awake();
  86733. };
  86734. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86735. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86736. if (minDistance !== void 0) {
  86737. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86738. }
  86739. };
  86740. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86741. //TODO separate rotational and transational motors.
  86742. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86743. if (motor) {
  86744. motor.setMotor(speed, maxForce);
  86745. }
  86746. };
  86747. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86748. //TODO separate rotational and transational motors.
  86749. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86750. if (motor) {
  86751. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86752. }
  86753. };
  86754. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86755. var body = impostor.physicsBody;
  86756. mesh.position.x = body.position.x;
  86757. mesh.position.y = body.position.y;
  86758. mesh.position.z = body.position.z;
  86759. if (mesh.rotationQuaternion) {
  86760. mesh.rotationQuaternion.x = body.orientation.x;
  86761. mesh.rotationQuaternion.y = body.orientation.y;
  86762. mesh.rotationQuaternion.z = body.orientation.z;
  86763. mesh.rotationQuaternion.w = body.orientation.s;
  86764. }
  86765. };
  86766. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86767. return impostor.physicsBody.shapes.radius;
  86768. };
  86769. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86770. var shape = impostor.physicsBody.shapes;
  86771. result.x = shape.halfWidth * 2;
  86772. result.y = shape.halfHeight * 2;
  86773. result.z = shape.halfDepth * 2;
  86774. };
  86775. OimoJSPlugin.prototype.dispose = function () {
  86776. this.world.clear();
  86777. };
  86778. return OimoJSPlugin;
  86779. }());
  86780. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86781. })(BABYLON || (BABYLON = {}));
  86782. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86783. var BABYLON;
  86784. (function (BABYLON) {
  86785. /*
  86786. * Based on jsTGALoader - Javascript loader for TGA file
  86787. * By Vincent Thibault
  86788. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86789. */
  86790. var TGATools = /** @class */ (function () {
  86791. function TGATools() {
  86792. }
  86793. TGATools.GetTGAHeader = function (data) {
  86794. var offset = 0;
  86795. var header = {
  86796. id_length: data[offset++],
  86797. colormap_type: data[offset++],
  86798. image_type: data[offset++],
  86799. colormap_index: data[offset++] | data[offset++] << 8,
  86800. colormap_length: data[offset++] | data[offset++] << 8,
  86801. colormap_size: data[offset++],
  86802. origin: [
  86803. data[offset++] | data[offset++] << 8,
  86804. data[offset++] | data[offset++] << 8
  86805. ],
  86806. width: data[offset++] | data[offset++] << 8,
  86807. height: data[offset++] | data[offset++] << 8,
  86808. pixel_size: data[offset++],
  86809. flags: data[offset++]
  86810. };
  86811. return header;
  86812. };
  86813. /**
  86814. * Uploads TGA content to a Babylon Texture
  86815. * @hidden
  86816. */
  86817. TGATools.UploadContent = function (texture, data) {
  86818. // Not enough data to contain header ?
  86819. if (data.length < 19) {
  86820. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86821. return;
  86822. }
  86823. // Read Header
  86824. var offset = 18;
  86825. var header = TGATools.GetTGAHeader(data);
  86826. // Assume it's a valid Targa file.
  86827. if (header.id_length + offset > data.length) {
  86828. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86829. return;
  86830. }
  86831. // Skip not needed data
  86832. offset += header.id_length;
  86833. var use_rle = false;
  86834. var use_pal = false;
  86835. var use_grey = false;
  86836. // Get some informations.
  86837. switch (header.image_type) {
  86838. case TGATools._TYPE_RLE_INDEXED:
  86839. use_rle = true;
  86840. case TGATools._TYPE_INDEXED:
  86841. use_pal = true;
  86842. break;
  86843. case TGATools._TYPE_RLE_RGB:
  86844. use_rle = true;
  86845. case TGATools._TYPE_RGB:
  86846. // use_rgb = true;
  86847. break;
  86848. case TGATools._TYPE_RLE_GREY:
  86849. use_rle = true;
  86850. case TGATools._TYPE_GREY:
  86851. use_grey = true;
  86852. break;
  86853. }
  86854. var pixel_data;
  86855. // var numAlphaBits = header.flags & 0xf;
  86856. var pixel_size = header.pixel_size >> 3;
  86857. var pixel_total = header.width * header.height * pixel_size;
  86858. // Read palettes
  86859. var palettes;
  86860. if (use_pal) {
  86861. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86862. }
  86863. // Read LRE
  86864. if (use_rle) {
  86865. pixel_data = new Uint8Array(pixel_total);
  86866. var c, count, i;
  86867. var localOffset = 0;
  86868. var pixels = new Uint8Array(pixel_size);
  86869. while (offset < pixel_total && localOffset < pixel_total) {
  86870. c = data[offset++];
  86871. count = (c & 0x7f) + 1;
  86872. // RLE pixels
  86873. if (c & 0x80) {
  86874. // Bind pixel tmp array
  86875. for (i = 0; i < pixel_size; ++i) {
  86876. pixels[i] = data[offset++];
  86877. }
  86878. // Copy pixel array
  86879. for (i = 0; i < count; ++i) {
  86880. pixel_data.set(pixels, localOffset + i * pixel_size);
  86881. }
  86882. localOffset += pixel_size * count;
  86883. }
  86884. // Raw pixels
  86885. else {
  86886. count *= pixel_size;
  86887. for (i = 0; i < count; ++i) {
  86888. pixel_data[localOffset + i] = data[offset++];
  86889. }
  86890. localOffset += count;
  86891. }
  86892. }
  86893. }
  86894. // RAW Pixels
  86895. else {
  86896. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86897. }
  86898. // Load to texture
  86899. var x_start, y_start, x_step, y_step, y_end, x_end;
  86900. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86901. default:
  86902. case TGATools._ORIGIN_UL:
  86903. x_start = 0;
  86904. x_step = 1;
  86905. x_end = header.width;
  86906. y_start = 0;
  86907. y_step = 1;
  86908. y_end = header.height;
  86909. break;
  86910. case TGATools._ORIGIN_BL:
  86911. x_start = 0;
  86912. x_step = 1;
  86913. x_end = header.width;
  86914. y_start = header.height - 1;
  86915. y_step = -1;
  86916. y_end = -1;
  86917. break;
  86918. case TGATools._ORIGIN_UR:
  86919. x_start = header.width - 1;
  86920. x_step = -1;
  86921. x_end = -1;
  86922. y_start = 0;
  86923. y_step = 1;
  86924. y_end = header.height;
  86925. break;
  86926. case TGATools._ORIGIN_BR:
  86927. x_start = header.width - 1;
  86928. x_step = -1;
  86929. x_end = -1;
  86930. y_start = header.height - 1;
  86931. y_step = -1;
  86932. y_end = -1;
  86933. break;
  86934. }
  86935. // Load the specify method
  86936. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86937. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86938. var engine = texture.getEngine();
  86939. engine._uploadDataToTextureDirectly(texture, imageData);
  86940. };
  86941. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86942. var image = pixel_data, colormap = palettes;
  86943. var width = header.width, height = header.height;
  86944. var color, i = 0, x, y;
  86945. var imageData = new Uint8Array(width * height * 4);
  86946. for (y = y_start; y !== y_end; y += y_step) {
  86947. for (x = x_start; x !== x_end; x += x_step, i++) {
  86948. color = image[i];
  86949. imageData[(x + width * y) * 4 + 3] = 255;
  86950. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86951. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86952. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86953. }
  86954. }
  86955. return imageData;
  86956. };
  86957. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86958. var image = pixel_data;
  86959. var width = header.width, height = header.height;
  86960. var color, i = 0, x, y;
  86961. var imageData = new Uint8Array(width * height * 4);
  86962. for (y = y_start; y !== y_end; y += y_step) {
  86963. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86964. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86965. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86966. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86967. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86968. imageData[(x + width * y) * 4 + 0] = r;
  86969. imageData[(x + width * y) * 4 + 1] = g;
  86970. imageData[(x + width * y) * 4 + 2] = b;
  86971. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86972. }
  86973. }
  86974. return imageData;
  86975. };
  86976. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86977. var image = pixel_data;
  86978. var width = header.width, height = header.height;
  86979. var i = 0, x, y;
  86980. var imageData = new Uint8Array(width * height * 4);
  86981. for (y = y_start; y !== y_end; y += y_step) {
  86982. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86983. imageData[(x + width * y) * 4 + 3] = 255;
  86984. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86985. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86986. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86987. }
  86988. }
  86989. return imageData;
  86990. };
  86991. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86992. var image = pixel_data;
  86993. var width = header.width, height = header.height;
  86994. var i = 0, x, y;
  86995. var imageData = new Uint8Array(width * height * 4);
  86996. for (y = y_start; y !== y_end; y += y_step) {
  86997. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86998. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86999. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87000. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87001. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87002. }
  87003. }
  87004. return imageData;
  87005. };
  87006. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87007. var image = pixel_data;
  87008. var width = header.width, height = header.height;
  87009. var color, i = 0, x, y;
  87010. var imageData = new Uint8Array(width * height * 4);
  87011. for (y = y_start; y !== y_end; y += y_step) {
  87012. for (x = x_start; x !== x_end; x += x_step, i++) {
  87013. color = image[i];
  87014. imageData[(x + width * y) * 4 + 0] = color;
  87015. imageData[(x + width * y) * 4 + 1] = color;
  87016. imageData[(x + width * y) * 4 + 2] = color;
  87017. imageData[(x + width * y) * 4 + 3] = 255;
  87018. }
  87019. }
  87020. return imageData;
  87021. };
  87022. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87023. var image = pixel_data;
  87024. var width = header.width, height = header.height;
  87025. var i = 0, x, y;
  87026. var imageData = new Uint8Array(width * height * 4);
  87027. for (y = y_start; y !== y_end; y += y_step) {
  87028. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87029. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87030. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87031. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87032. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87033. }
  87034. }
  87035. return imageData;
  87036. };
  87037. //private static _TYPE_NO_DATA = 0;
  87038. TGATools._TYPE_INDEXED = 1;
  87039. TGATools._TYPE_RGB = 2;
  87040. TGATools._TYPE_GREY = 3;
  87041. TGATools._TYPE_RLE_INDEXED = 9;
  87042. TGATools._TYPE_RLE_RGB = 10;
  87043. TGATools._TYPE_RLE_GREY = 11;
  87044. TGATools._ORIGIN_MASK = 0x30;
  87045. TGATools._ORIGIN_SHIFT = 0x04;
  87046. TGATools._ORIGIN_BL = 0x00;
  87047. TGATools._ORIGIN_BR = 0x01;
  87048. TGATools._ORIGIN_UL = 0x02;
  87049. TGATools._ORIGIN_UR = 0x03;
  87050. return TGATools;
  87051. }());
  87052. BABYLON.TGATools = TGATools;
  87053. })(BABYLON || (BABYLON = {}));
  87054. //# sourceMappingURL=babylon.tga.js.map
  87055. var BABYLON;
  87056. (function (BABYLON) {
  87057. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87058. // All values and structures referenced from:
  87059. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87060. var DDS_MAGIC = 0x20534444;
  87061. var
  87062. //DDSD_CAPS = 0x1,
  87063. //DDSD_HEIGHT = 0x2,
  87064. //DDSD_WIDTH = 0x4,
  87065. //DDSD_PITCH = 0x8,
  87066. //DDSD_PIXELFORMAT = 0x1000,
  87067. DDSD_MIPMAPCOUNT = 0x20000;
  87068. //DDSD_LINEARSIZE = 0x80000,
  87069. //DDSD_DEPTH = 0x800000;
  87070. // var DDSCAPS_COMPLEX = 0x8,
  87071. // DDSCAPS_MIPMAP = 0x400000,
  87072. // DDSCAPS_TEXTURE = 0x1000;
  87073. var DDSCAPS2_CUBEMAP = 0x200;
  87074. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87075. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87076. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87077. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87078. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87079. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87080. // DDSCAPS2_VOLUME = 0x200000;
  87081. var
  87082. //DDPF_ALPHAPIXELS = 0x1,
  87083. //DDPF_ALPHA = 0x2,
  87084. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87085. //DDPF_YUV = 0x200,
  87086. DDPF_LUMINANCE = 0x20000;
  87087. function FourCCToInt32(value) {
  87088. return value.charCodeAt(0) +
  87089. (value.charCodeAt(1) << 8) +
  87090. (value.charCodeAt(2) << 16) +
  87091. (value.charCodeAt(3) << 24);
  87092. }
  87093. function Int32ToFourCC(value) {
  87094. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87095. }
  87096. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87097. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87098. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87099. var FOURCC_DX10 = FourCCToInt32("DX10");
  87100. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87101. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87102. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87103. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87104. var headerLengthInt = 31; // The header length in 32 bit ints
  87105. // Offsets into the header array
  87106. var off_magic = 0;
  87107. var off_size = 1;
  87108. var off_flags = 2;
  87109. var off_height = 3;
  87110. var off_width = 4;
  87111. var off_mipmapCount = 7;
  87112. var off_pfFlags = 20;
  87113. var off_pfFourCC = 21;
  87114. var off_RGBbpp = 22;
  87115. var off_RMask = 23;
  87116. var off_GMask = 24;
  87117. var off_BMask = 25;
  87118. var off_AMask = 26;
  87119. // var off_caps1 = 27;
  87120. var off_caps2 = 28;
  87121. // var off_caps3 = 29;
  87122. // var off_caps4 = 30;
  87123. var off_dxgiFormat = 32;
  87124. ;
  87125. var DDSTools = /** @class */ (function () {
  87126. function DDSTools() {
  87127. }
  87128. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87129. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87130. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87131. var mipmapCount = 1;
  87132. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87133. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87134. }
  87135. var fourCC = header[off_pfFourCC];
  87136. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87137. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87138. switch (fourCC) {
  87139. case FOURCC_D3DFMT_R16G16B16A16F:
  87140. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87141. break;
  87142. case FOURCC_D3DFMT_R32G32B32A32F:
  87143. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87144. break;
  87145. case FOURCC_DX10:
  87146. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87147. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87148. break;
  87149. }
  87150. }
  87151. return {
  87152. width: header[off_width],
  87153. height: header[off_height],
  87154. mipmapCount: mipmapCount,
  87155. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87156. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87157. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87158. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87159. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87160. dxgiFormat: dxgiFormat,
  87161. textureType: textureType
  87162. };
  87163. };
  87164. DDSTools._ToHalfFloat = function (value) {
  87165. if (!DDSTools._FloatView) {
  87166. DDSTools._FloatView = new Float32Array(1);
  87167. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87168. }
  87169. DDSTools._FloatView[0] = value;
  87170. var x = DDSTools._Int32View[0];
  87171. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87172. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87173. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87174. /* If zero, or denormal, or exponent underflows too much for a denormal
  87175. * half, return signed zero. */
  87176. if (e < 103) {
  87177. return bits;
  87178. }
  87179. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87180. if (e > 142) {
  87181. bits |= 0x7c00;
  87182. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87183. * not Inf, so make sure we set one mantissa bit too. */
  87184. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87185. return bits;
  87186. }
  87187. /* If exponent underflows but not too much, return a denormal */
  87188. if (e < 113) {
  87189. m |= 0x0800;
  87190. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87191. * to 1, which is OK. */
  87192. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87193. return bits;
  87194. }
  87195. bits |= ((e - 112) << 10) | (m >> 1);
  87196. bits += m & 1;
  87197. return bits;
  87198. };
  87199. DDSTools._FromHalfFloat = function (value) {
  87200. var s = (value & 0x8000) >> 15;
  87201. var e = (value & 0x7C00) >> 10;
  87202. var f = value & 0x03FF;
  87203. if (e === 0) {
  87204. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87205. }
  87206. else if (e == 0x1F) {
  87207. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87208. }
  87209. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87210. };
  87211. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87212. var destArray = new Float32Array(dataLength);
  87213. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87214. var index = 0;
  87215. for (var y = 0; y < height; y++) {
  87216. for (var x = 0; x < width; x++) {
  87217. var srcPos = (x + y * width) * 4;
  87218. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87219. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87220. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87221. if (DDSTools.StoreLODInAlphaChannel) {
  87222. destArray[index + 3] = lod;
  87223. }
  87224. else {
  87225. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87226. }
  87227. index += 4;
  87228. }
  87229. }
  87230. return destArray;
  87231. };
  87232. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87233. if (DDSTools.StoreLODInAlphaChannel) {
  87234. var destArray = new Uint16Array(dataLength);
  87235. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87236. var index = 0;
  87237. for (var y = 0; y < height; y++) {
  87238. for (var x = 0; x < width; x++) {
  87239. var srcPos = (x + y * width) * 4;
  87240. destArray[index] = srcData[srcPos];
  87241. destArray[index + 1] = srcData[srcPos + 1];
  87242. destArray[index + 2] = srcData[srcPos + 2];
  87243. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87244. index += 4;
  87245. }
  87246. }
  87247. return destArray;
  87248. }
  87249. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87250. };
  87251. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87252. if (DDSTools.StoreLODInAlphaChannel) {
  87253. var destArray = new Float32Array(dataLength);
  87254. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87255. var index = 0;
  87256. for (var y = 0; y < height; y++) {
  87257. for (var x = 0; x < width; x++) {
  87258. var srcPos = (x + y * width) * 4;
  87259. destArray[index] = srcData[srcPos];
  87260. destArray[index + 1] = srcData[srcPos + 1];
  87261. destArray[index + 2] = srcData[srcPos + 2];
  87262. destArray[index + 3] = lod;
  87263. index += 4;
  87264. }
  87265. }
  87266. return destArray;
  87267. }
  87268. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87269. };
  87270. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87271. var destArray = new Uint8Array(dataLength);
  87272. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87273. var index = 0;
  87274. for (var y = 0; y < height; y++) {
  87275. for (var x = 0; x < width; x++) {
  87276. var srcPos = (x + y * width) * 4;
  87277. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87278. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87279. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87280. if (DDSTools.StoreLODInAlphaChannel) {
  87281. destArray[index + 3] = lod;
  87282. }
  87283. else {
  87284. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87285. }
  87286. index += 4;
  87287. }
  87288. }
  87289. return destArray;
  87290. };
  87291. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87292. var destArray = new Uint8Array(dataLength);
  87293. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87294. var index = 0;
  87295. for (var y = 0; y < height; y++) {
  87296. for (var x = 0; x < width; x++) {
  87297. var srcPos = (x + y * width) * 4;
  87298. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87299. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87300. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87301. if (DDSTools.StoreLODInAlphaChannel) {
  87302. destArray[index + 3] = lod;
  87303. }
  87304. else {
  87305. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87306. }
  87307. index += 4;
  87308. }
  87309. }
  87310. return destArray;
  87311. };
  87312. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87313. var byteArray = new Uint8Array(dataLength);
  87314. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87315. var index = 0;
  87316. for (var y = 0; y < height; y++) {
  87317. for (var x = 0; x < width; x++) {
  87318. var srcPos = (x + y * width) * 4;
  87319. byteArray[index] = srcData[srcPos + rOffset];
  87320. byteArray[index + 1] = srcData[srcPos + gOffset];
  87321. byteArray[index + 2] = srcData[srcPos + bOffset];
  87322. byteArray[index + 3] = srcData[srcPos + aOffset];
  87323. index += 4;
  87324. }
  87325. }
  87326. return byteArray;
  87327. };
  87328. DDSTools._ExtractLongWordOrder = function (value) {
  87329. if (value === 0 || value === 255 || value === -16777216) {
  87330. return 0;
  87331. }
  87332. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87333. };
  87334. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87335. var byteArray = new Uint8Array(dataLength);
  87336. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87337. var index = 0;
  87338. for (var y = 0; y < height; y++) {
  87339. for (var x = 0; x < width; x++) {
  87340. var srcPos = (x + y * width) * 3;
  87341. byteArray[index] = srcData[srcPos + rOffset];
  87342. byteArray[index + 1] = srcData[srcPos + gOffset];
  87343. byteArray[index + 2] = srcData[srcPos + bOffset];
  87344. index += 3;
  87345. }
  87346. }
  87347. return byteArray;
  87348. };
  87349. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87350. var byteArray = new Uint8Array(dataLength);
  87351. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87352. var index = 0;
  87353. for (var y = 0; y < height; y++) {
  87354. for (var x = 0; x < width; x++) {
  87355. var srcPos = (x + y * width);
  87356. byteArray[index] = srcData[srcPos];
  87357. index++;
  87358. }
  87359. }
  87360. return byteArray;
  87361. };
  87362. /**
  87363. * Uploads DDS Levels to a Babylon Texture
  87364. * @hidden
  87365. */
  87366. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87367. if (lodIndex === void 0) { lodIndex = -1; }
  87368. var sphericalPolynomialFaces = null;
  87369. if (info.sphericalPolynomial) {
  87370. sphericalPolynomialFaces = new Array();
  87371. }
  87372. var ext = engine.getCaps().s3tc;
  87373. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87374. var fourCC, width, height, dataLength = 0, dataOffset;
  87375. var byteArray, mipmapCount, mip;
  87376. var internalCompressedFormat = 0;
  87377. var blockBytes = 1;
  87378. if (header[off_magic] !== DDS_MAGIC) {
  87379. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87380. return;
  87381. }
  87382. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87383. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87384. return;
  87385. }
  87386. if (info.isCompressed && !ext) {
  87387. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87388. return;
  87389. }
  87390. var bpp = header[off_RGBbpp];
  87391. dataOffset = header[off_size] + 4;
  87392. var computeFormats = false;
  87393. if (info.isFourCC) {
  87394. fourCC = header[off_pfFourCC];
  87395. switch (fourCC) {
  87396. case FOURCC_DXT1:
  87397. blockBytes = 8;
  87398. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87399. break;
  87400. case FOURCC_DXT3:
  87401. blockBytes = 16;
  87402. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87403. break;
  87404. case FOURCC_DXT5:
  87405. blockBytes = 16;
  87406. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87407. break;
  87408. case FOURCC_D3DFMT_R16G16B16A16F:
  87409. computeFormats = true;
  87410. break;
  87411. case FOURCC_D3DFMT_R32G32B32A32F:
  87412. computeFormats = true;
  87413. break;
  87414. case FOURCC_DX10:
  87415. // There is an additionnal header so dataOffset need to be changed
  87416. dataOffset += 5 * 4; // 5 uints
  87417. var supported = false;
  87418. switch (info.dxgiFormat) {
  87419. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87420. computeFormats = true;
  87421. supported = true;
  87422. break;
  87423. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87424. info.isRGB = true;
  87425. info.isFourCC = false;
  87426. bpp = 32;
  87427. supported = true;
  87428. break;
  87429. }
  87430. if (supported) {
  87431. break;
  87432. }
  87433. default:
  87434. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87435. return;
  87436. }
  87437. }
  87438. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87439. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87440. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87441. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87442. if (computeFormats) {
  87443. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87444. }
  87445. mipmapCount = 1;
  87446. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87447. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87448. }
  87449. for (var face = 0; face < faces; face++) {
  87450. width = header[off_width];
  87451. height = header[off_height];
  87452. for (mip = 0; mip < mipmapCount; ++mip) {
  87453. if (lodIndex === -1 || lodIndex === mip) {
  87454. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87455. var i = (lodIndex === -1) ? mip : 0;
  87456. if (!info.isCompressed && info.isFourCC) {
  87457. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87458. dataLength = width * height * 4;
  87459. var floatArray = null;
  87460. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87461. if (bpp === 128) {
  87462. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87463. if (sphericalPolynomialFaces && i == 0) {
  87464. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87465. }
  87466. }
  87467. else if (bpp === 64) {
  87468. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87469. if (sphericalPolynomialFaces && i == 0) {
  87470. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87471. }
  87472. }
  87473. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87474. }
  87475. else {
  87476. if (bpp === 128) {
  87477. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87478. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87479. if (sphericalPolynomialFaces && i == 0) {
  87480. sphericalPolynomialFaces.push(floatArray);
  87481. }
  87482. }
  87483. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87484. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87485. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87486. if (sphericalPolynomialFaces && i == 0) {
  87487. sphericalPolynomialFaces.push(floatArray);
  87488. }
  87489. }
  87490. else { // 64
  87491. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87492. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87493. if (sphericalPolynomialFaces && i == 0) {
  87494. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87495. }
  87496. }
  87497. }
  87498. if (floatArray) {
  87499. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87500. }
  87501. }
  87502. else if (info.isRGB) {
  87503. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87504. if (bpp === 24) {
  87505. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87506. dataLength = width * height * 3;
  87507. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87508. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87509. }
  87510. else { // 32
  87511. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87512. dataLength = width * height * 4;
  87513. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87514. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87515. }
  87516. }
  87517. else if (info.isLuminance) {
  87518. var unpackAlignment = engine._getUnpackAlignement();
  87519. var unpaddedRowSize = width;
  87520. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87521. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87522. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87523. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87524. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87525. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87526. }
  87527. else {
  87528. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87529. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87530. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87531. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87532. }
  87533. }
  87534. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87535. width *= 0.5;
  87536. height *= 0.5;
  87537. width = Math.max(1.0, width);
  87538. height = Math.max(1.0, height);
  87539. }
  87540. if (currentFace !== undefined) {
  87541. // Loading a single face
  87542. break;
  87543. }
  87544. }
  87545. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87546. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87547. size: header[off_width],
  87548. right: sphericalPolynomialFaces[0],
  87549. left: sphericalPolynomialFaces[1],
  87550. up: sphericalPolynomialFaces[2],
  87551. down: sphericalPolynomialFaces[3],
  87552. front: sphericalPolynomialFaces[4],
  87553. back: sphericalPolynomialFaces[5],
  87554. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87555. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87556. gammaSpace: false,
  87557. });
  87558. }
  87559. else {
  87560. info.sphericalPolynomial = undefined;
  87561. }
  87562. };
  87563. DDSTools.StoreLODInAlphaChannel = false;
  87564. return DDSTools;
  87565. }());
  87566. BABYLON.DDSTools = DDSTools;
  87567. })(BABYLON || (BABYLON = {}));
  87568. //# sourceMappingURL=babylon.dds.js.map
  87569. var BABYLON;
  87570. (function (BABYLON) {
  87571. /**
  87572. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87573. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87574. */
  87575. var KhronosTextureContainer = /** @class */ (function () {
  87576. /**
  87577. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87578. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87579. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87580. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87581. */
  87582. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87583. this.arrayBuffer = arrayBuffer;
  87584. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87585. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87586. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87587. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87588. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87589. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87590. BABYLON.Tools.Error("texture missing KTX identifier");
  87591. return;
  87592. }
  87593. // load the reset of the header in native 32 bit int
  87594. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87595. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87596. var oppositeEndianess = header[0] === 0x01020304;
  87597. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87598. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87599. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87600. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87601. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87602. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87603. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87604. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87605. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87606. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87607. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87608. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87609. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87610. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87611. if (this.glType !== 0) {
  87612. BABYLON.Tools.Error("only compressed formats currently supported");
  87613. return;
  87614. }
  87615. else {
  87616. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87617. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87618. }
  87619. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87620. BABYLON.Tools.Error("only 2D textures currently supported");
  87621. return;
  87622. }
  87623. if (this.numberOfArrayElements !== 0) {
  87624. BABYLON.Tools.Error("texture arrays not currently supported");
  87625. return;
  87626. }
  87627. if (this.numberOfFaces !== facesExpected) {
  87628. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87629. return;
  87630. }
  87631. // we now have a completely validated file, so could use existence of loadType as success
  87632. // would need to make this more elaborate & adjust checks above to support more than one load type
  87633. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87634. }
  87635. // not as fast hardware based, but will probably never need to use
  87636. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87637. return ((val & 0xFF) << 24)
  87638. | ((val & 0xFF00) << 8)
  87639. | ((val >> 8) & 0xFF00)
  87640. | ((val >> 24) & 0xFF);
  87641. };
  87642. /**
  87643. * Uploads KTX content to a Babylon Texture.
  87644. * It is assumed that the texture has already been created & is currently bound
  87645. * @hidden
  87646. */
  87647. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  87648. switch (this.loadType) {
  87649. case KhronosTextureContainer.COMPRESSED_2D:
  87650. this._upload2DCompressedLevels(texture, loadMipmaps);
  87651. break;
  87652. case KhronosTextureContainer.TEX_2D:
  87653. case KhronosTextureContainer.COMPRESSED_3D:
  87654. case KhronosTextureContainer.TEX_3D:
  87655. }
  87656. };
  87657. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  87658. // initialize width & height for level 1
  87659. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87660. var width = this.pixelWidth;
  87661. var height = this.pixelHeight;
  87662. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87663. for (var level = 0; level < mipmapCount; level++) {
  87664. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87665. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87666. for (var face = 0; face < this.numberOfFaces; face++) {
  87667. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87668. var engine = texture.getEngine();
  87669. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  87670. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87671. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87672. }
  87673. width = Math.max(1.0, width * 0.5);
  87674. height = Math.max(1.0, height * 0.5);
  87675. }
  87676. };
  87677. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87678. // load types
  87679. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87680. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87681. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87682. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87683. return KhronosTextureContainer;
  87684. }());
  87685. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87686. })(BABYLON || (BABYLON = {}));
  87687. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87688. var BABYLON;
  87689. (function (BABYLON) {
  87690. var Debug;
  87691. (function (Debug) {
  87692. /**
  87693. * Class used to render a debug view of a given skeleton
  87694. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87695. */
  87696. var SkeletonViewer = /** @class */ (function () {
  87697. /**
  87698. * Creates a new SkeletonViewer
  87699. * @param skeleton defines the skeleton to render
  87700. * @param mesh defines the mesh attached to the skeleton
  87701. * @param scene defines the hosting scene
  87702. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87703. * @param renderingGroupId defines the rendering group id to use with the viewer
  87704. */
  87705. function SkeletonViewer(
  87706. /** defines the skeleton to render */
  87707. skeleton,
  87708. /** defines the mesh attached to the skeleton */
  87709. mesh, scene,
  87710. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87711. autoUpdateBonesMatrices,
  87712. /** defines the rendering group id to use with the viewer */
  87713. renderingGroupId) {
  87714. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87715. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87716. this.skeleton = skeleton;
  87717. this.mesh = mesh;
  87718. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87719. this.renderingGroupId = renderingGroupId;
  87720. /** Gets or sets the color used to render the skeleton */
  87721. this.color = BABYLON.Color3.White();
  87722. this._debugLines = new Array();
  87723. this._isEnabled = false;
  87724. this._scene = scene;
  87725. this.update();
  87726. this._renderFunction = this.update.bind(this);
  87727. }
  87728. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87729. get: function () {
  87730. return this._isEnabled;
  87731. },
  87732. /** Gets or sets a boolean indicating if the viewer is enabled */
  87733. set: function (value) {
  87734. if (this._isEnabled === value) {
  87735. return;
  87736. }
  87737. this._isEnabled = value;
  87738. if (value) {
  87739. this._scene.registerBeforeRender(this._renderFunction);
  87740. }
  87741. else {
  87742. this._scene.unregisterBeforeRender(this._renderFunction);
  87743. }
  87744. },
  87745. enumerable: true,
  87746. configurable: true
  87747. });
  87748. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87749. if (x === void 0) { x = 0; }
  87750. if (y === void 0) { y = 0; }
  87751. if (z === void 0) { z = 0; }
  87752. var tmat = BABYLON.Tmp.Matrix[0];
  87753. var parentBone = bone.getParent();
  87754. tmat.copyFrom(bone.getLocalMatrix());
  87755. if (x !== 0 || y !== 0 || z !== 0) {
  87756. var tmat2 = BABYLON.Tmp.Matrix[1];
  87757. BABYLON.Matrix.IdentityToRef(tmat2);
  87758. tmat2.m[12] = x;
  87759. tmat2.m[13] = y;
  87760. tmat2.m[14] = z;
  87761. tmat2.multiplyToRef(tmat, tmat);
  87762. }
  87763. if (parentBone) {
  87764. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87765. }
  87766. tmat.multiplyToRef(meshMat, tmat);
  87767. position.x = tmat.m[12];
  87768. position.y = tmat.m[13];
  87769. position.z = tmat.m[14];
  87770. };
  87771. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87772. var len = bones.length;
  87773. var meshPos = this.mesh.position;
  87774. for (var i = 0; i < len; i++) {
  87775. var bone = bones[i];
  87776. var points = this._debugLines[i];
  87777. if (!points) {
  87778. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87779. this._debugLines[i] = points;
  87780. }
  87781. this._getBonePosition(points[0], bone, meshMat);
  87782. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87783. points[0].subtractInPlace(meshPos);
  87784. points[1].subtractInPlace(meshPos);
  87785. }
  87786. };
  87787. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87788. var len = bones.length;
  87789. var boneNum = 0;
  87790. var meshPos = this.mesh.position;
  87791. for (var i = len - 1; i >= 0; i--) {
  87792. var childBone = bones[i];
  87793. var parentBone = childBone.getParent();
  87794. if (!parentBone) {
  87795. continue;
  87796. }
  87797. var points = this._debugLines[boneNum];
  87798. if (!points) {
  87799. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87800. this._debugLines[boneNum] = points;
  87801. }
  87802. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87803. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87804. points[0].subtractInPlace(meshPos);
  87805. points[1].subtractInPlace(meshPos);
  87806. boneNum++;
  87807. }
  87808. };
  87809. /** Update the viewer to sync with current skeleton state */
  87810. SkeletonViewer.prototype.update = function () {
  87811. if (this.autoUpdateBonesMatrices) {
  87812. this.skeleton.computeAbsoluteTransforms();
  87813. }
  87814. if (this.skeleton.bones[0].length === undefined) {
  87815. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87816. }
  87817. else {
  87818. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87819. }
  87820. if (!this._debugMesh) {
  87821. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87822. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87823. }
  87824. else {
  87825. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87826. }
  87827. this._debugMesh.position.copyFrom(this.mesh.position);
  87828. this._debugMesh.color = this.color;
  87829. };
  87830. /** Release associated resources */
  87831. SkeletonViewer.prototype.dispose = function () {
  87832. if (this._debugMesh) {
  87833. this.isEnabled = false;
  87834. this._debugMesh.dispose();
  87835. this._debugMesh = null;
  87836. }
  87837. };
  87838. return SkeletonViewer;
  87839. }());
  87840. Debug.SkeletonViewer = SkeletonViewer;
  87841. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87842. })(BABYLON || (BABYLON = {}));
  87843. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87844. /**
  87845. * Module Debug contains the (visual) components to debug a scene correctly
  87846. */
  87847. var BABYLON;
  87848. (function (BABYLON) {
  87849. var Debug;
  87850. (function (Debug) {
  87851. /**
  87852. * The Axes viewer will show 3 axes in a specific point in space
  87853. */
  87854. var AxesViewer = /** @class */ (function () {
  87855. /**
  87856. * Creates a new AxesViewer
  87857. * @param scene defines the hosting scene
  87858. * @param scaleLines defines a number used to scale line length (1 by default)
  87859. */
  87860. function AxesViewer(scene, scaleLines) {
  87861. if (scaleLines === void 0) { scaleLines = 1; }
  87862. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87863. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87864. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87865. /**
  87866. * Gets or sets a number used to scale line length
  87867. */
  87868. this.scaleLines = 1;
  87869. this.scaleLines = scaleLines;
  87870. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87871. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87872. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87873. this._xmesh.renderingGroupId = 2;
  87874. this._ymesh.renderingGroupId = 2;
  87875. this._zmesh.renderingGroupId = 2;
  87876. this._xmesh.material.checkReadyOnlyOnce = true;
  87877. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87878. this._ymesh.material.checkReadyOnlyOnce = true;
  87879. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87880. this._zmesh.material.checkReadyOnlyOnce = true;
  87881. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87882. this.scene = scene;
  87883. }
  87884. /**
  87885. * Force the viewer to update
  87886. * @param position defines the position of the viewer
  87887. * @param xaxis defines the x axis of the viewer
  87888. * @param yaxis defines the y axis of the viewer
  87889. * @param zaxis defines the z axis of the viewer
  87890. */
  87891. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87892. var scaleLines = this.scaleLines;
  87893. if (this._xmesh) {
  87894. this._xmesh.position.copyFrom(position);
  87895. }
  87896. if (this._ymesh) {
  87897. this._ymesh.position.copyFrom(position);
  87898. }
  87899. if (this._zmesh) {
  87900. this._zmesh.position.copyFrom(position);
  87901. }
  87902. var point2 = this._xline[1];
  87903. point2.x = xaxis.x * scaleLines;
  87904. point2.y = xaxis.y * scaleLines;
  87905. point2.z = xaxis.z * scaleLines;
  87906. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87907. point2 = this._yline[1];
  87908. point2.x = yaxis.x * scaleLines;
  87909. point2.y = yaxis.y * scaleLines;
  87910. point2.z = yaxis.z * scaleLines;
  87911. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87912. point2 = this._zline[1];
  87913. point2.x = zaxis.x * scaleLines;
  87914. point2.y = zaxis.y * scaleLines;
  87915. point2.z = zaxis.z * scaleLines;
  87916. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87917. };
  87918. /** Releases resources */
  87919. AxesViewer.prototype.dispose = function () {
  87920. if (this._xmesh) {
  87921. this._xmesh.dispose();
  87922. }
  87923. if (this._ymesh) {
  87924. this._ymesh.dispose();
  87925. }
  87926. if (this._zmesh) {
  87927. this._zmesh.dispose();
  87928. }
  87929. this._xmesh = null;
  87930. this._ymesh = null;
  87931. this._zmesh = null;
  87932. this.scene = null;
  87933. };
  87934. return AxesViewer;
  87935. }());
  87936. Debug.AxesViewer = AxesViewer;
  87937. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87938. })(BABYLON || (BABYLON = {}));
  87939. //# sourceMappingURL=babylon.axesViewer.js.map
  87940. var BABYLON;
  87941. (function (BABYLON) {
  87942. var Debug;
  87943. (function (Debug) {
  87944. /**
  87945. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87946. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87947. */
  87948. var BoneAxesViewer = /** @class */ (function (_super) {
  87949. __extends(BoneAxesViewer, _super);
  87950. /**
  87951. * Creates a new BoneAxesViewer
  87952. * @param scene defines the hosting scene
  87953. * @param bone defines the target bone
  87954. * @param mesh defines the target mesh
  87955. * @param scaleLines defines a scaling factor for line length (1 by default)
  87956. */
  87957. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87958. if (scaleLines === void 0) { scaleLines = 1; }
  87959. var _this = _super.call(this, scene, scaleLines) || this;
  87960. /** Gets current position */
  87961. _this.pos = BABYLON.Vector3.Zero();
  87962. /** Gets direction of X axis */
  87963. _this.xaxis = BABYLON.Vector3.Zero();
  87964. /** Gets direction of Y axis */
  87965. _this.yaxis = BABYLON.Vector3.Zero();
  87966. /** Gets direction of Z axis */
  87967. _this.zaxis = BABYLON.Vector3.Zero();
  87968. _this.mesh = mesh;
  87969. _this.bone = bone;
  87970. return _this;
  87971. }
  87972. /**
  87973. * Force the viewer to update
  87974. */
  87975. BoneAxesViewer.prototype.update = function () {
  87976. if (!this.mesh || !this.bone) {
  87977. return;
  87978. }
  87979. var bone = this.bone;
  87980. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87981. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87982. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87983. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87984. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87985. };
  87986. /** Releases resources */
  87987. BoneAxesViewer.prototype.dispose = function () {
  87988. if (this.mesh) {
  87989. this.mesh = null;
  87990. this.bone = null;
  87991. _super.prototype.dispose.call(this);
  87992. }
  87993. };
  87994. return BoneAxesViewer;
  87995. }(Debug.AxesViewer));
  87996. Debug.BoneAxesViewer = BoneAxesViewer;
  87997. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87998. })(BABYLON || (BABYLON = {}));
  87999. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88000. var BABYLON;
  88001. (function (BABYLON) {
  88002. var RayHelper = /** @class */ (function () {
  88003. function RayHelper(ray) {
  88004. this.ray = ray;
  88005. }
  88006. RayHelper.CreateAndShow = function (ray, scene, color) {
  88007. var helper = new RayHelper(ray);
  88008. helper.show(scene, color);
  88009. return helper;
  88010. };
  88011. RayHelper.prototype.show = function (scene, color) {
  88012. if (!this._renderFunction && this.ray) {
  88013. var ray = this.ray;
  88014. this._renderFunction = this._render.bind(this);
  88015. this._scene = scene;
  88016. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88017. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88018. if (this._renderFunction) {
  88019. this._scene.registerBeforeRender(this._renderFunction);
  88020. }
  88021. }
  88022. if (color && this._renderLine) {
  88023. this._renderLine.color.copyFrom(color);
  88024. }
  88025. };
  88026. RayHelper.prototype.hide = function () {
  88027. if (this._renderFunction && this._scene) {
  88028. this._scene.unregisterBeforeRender(this._renderFunction);
  88029. this._scene = null;
  88030. this._renderFunction = null;
  88031. if (this._renderLine) {
  88032. this._renderLine.dispose();
  88033. this._renderLine = null;
  88034. }
  88035. this._renderPoints = [];
  88036. }
  88037. };
  88038. RayHelper.prototype._render = function () {
  88039. var ray = this.ray;
  88040. if (!ray) {
  88041. return;
  88042. }
  88043. var point = this._renderPoints[1];
  88044. var len = Math.min(ray.length, 1000000);
  88045. point.copyFrom(ray.direction);
  88046. point.scaleInPlace(len);
  88047. point.addInPlace(ray.origin);
  88048. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88049. };
  88050. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88051. this._attachedToMesh = mesh;
  88052. var ray = this.ray;
  88053. if (!ray) {
  88054. return;
  88055. }
  88056. if (!ray.direction) {
  88057. ray.direction = BABYLON.Vector3.Zero();
  88058. }
  88059. if (!ray.origin) {
  88060. ray.origin = BABYLON.Vector3.Zero();
  88061. }
  88062. if (length) {
  88063. ray.length = length;
  88064. }
  88065. if (!meshSpaceOrigin) {
  88066. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88067. }
  88068. if (!meshSpaceDirection) {
  88069. // -1 so that this will work with Mesh.lookAt
  88070. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88071. }
  88072. if (!this._meshSpaceDirection) {
  88073. this._meshSpaceDirection = meshSpaceDirection.clone();
  88074. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88075. }
  88076. else {
  88077. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88078. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88079. }
  88080. if (!this._updateToMeshFunction) {
  88081. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88082. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88083. }
  88084. this._updateToMesh();
  88085. };
  88086. RayHelper.prototype.detachFromMesh = function () {
  88087. if (this._attachedToMesh) {
  88088. if (this._updateToMeshFunction) {
  88089. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88090. }
  88091. this._attachedToMesh = null;
  88092. this._updateToMeshFunction = null;
  88093. }
  88094. };
  88095. RayHelper.prototype._updateToMesh = function () {
  88096. var ray = this.ray;
  88097. if (!this._attachedToMesh || !ray) {
  88098. return;
  88099. }
  88100. if (this._attachedToMesh._isDisposed) {
  88101. this.detachFromMesh();
  88102. return;
  88103. }
  88104. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88105. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88106. };
  88107. RayHelper.prototype.dispose = function () {
  88108. this.hide();
  88109. this.detachFromMesh();
  88110. this.ray = null;
  88111. };
  88112. return RayHelper;
  88113. }());
  88114. BABYLON.RayHelper = RayHelper;
  88115. })(BABYLON || (BABYLON = {}));
  88116. //# sourceMappingURL=babylon.rayHelper.js.map
  88117. var BABYLON;
  88118. (function (BABYLON) {
  88119. // load the inspector using require, if not present in the global namespace.
  88120. var DebugLayer = /** @class */ (function () {
  88121. function DebugLayer(scene) {
  88122. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88123. this.onPropertyChangedObservable = new BABYLON.Observable();
  88124. this._scene = scene;
  88125. }
  88126. /** Creates the inspector window. */
  88127. DebugLayer.prototype._createInspector = function (config) {
  88128. if (config === void 0) { config = {}; }
  88129. var popup = config.popup || false;
  88130. var initialTab = config.initialTab || 0;
  88131. var parentElement = config.parentElement || null;
  88132. if (!this._inspector) {
  88133. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88134. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88135. } // else nothing to do as instance is already created
  88136. };
  88137. DebugLayer.prototype.isVisible = function () {
  88138. if (!this._inspector) {
  88139. return false;
  88140. }
  88141. return true;
  88142. };
  88143. DebugLayer.prototype.hide = function () {
  88144. if (this._inspector) {
  88145. try {
  88146. this._inspector.dispose();
  88147. }
  88148. catch (e) {
  88149. // If the inspector has been removed directly from the inspector tool
  88150. }
  88151. this.onPropertyChangedObservable.clear();
  88152. this._inspector = null;
  88153. }
  88154. };
  88155. /**
  88156. *
  88157. * Launch the debugLayer.
  88158. *
  88159. * initialTab:
  88160. * | Value | Tab Name |
  88161. * | --- | --- |
  88162. * | 0 | Scene |
  88163. * | 1 | Console |
  88164. * | 2 | Stats |
  88165. * | 3 | Textures |
  88166. * | 4 | Mesh |
  88167. * | 5 | Light |
  88168. * | 6 | Material |
  88169. * | 7 | GLTF |
  88170. * | 8 | GUI |
  88171. * | 9 | Physics |
  88172. * | 10 | Camera |
  88173. * | 11 | Audio |
  88174. *
  88175. */
  88176. DebugLayer.prototype.show = function (config) {
  88177. if (config === void 0) { config = {}; }
  88178. if (typeof this.BJSINSPECTOR == 'undefined') {
  88179. // Load inspector and add it to the DOM
  88180. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88181. }
  88182. else {
  88183. // Otherwise creates the inspector
  88184. this._createInspector(config);
  88185. }
  88186. };
  88187. /**
  88188. * Gets the active tab
  88189. * @return the index of the active tab or -1 if the inspector is hidden
  88190. */
  88191. DebugLayer.prototype.getActiveTab = function () {
  88192. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88193. };
  88194. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88195. return DebugLayer;
  88196. }());
  88197. BABYLON.DebugLayer = DebugLayer;
  88198. })(BABYLON || (BABYLON = {}));
  88199. //# sourceMappingURL=babylon.debugLayer.js.map
  88200. var BABYLON;
  88201. (function (BABYLON) {
  88202. var Debug;
  88203. (function (Debug) {
  88204. /**
  88205. * Used to show the physics impostor around the specific mesh
  88206. */
  88207. var PhysicsViewer = /** @class */ (function () {
  88208. /**
  88209. * Creates a new PhysicsViewer
  88210. * @param scene defines the hosting scene
  88211. */
  88212. function PhysicsViewer(scene) {
  88213. /** @hidden */
  88214. this._impostors = [];
  88215. /** @hidden */
  88216. this._meshes = [];
  88217. /** @hidden */
  88218. this._numMeshes = 0;
  88219. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88220. var physicEngine = this._scene.getPhysicsEngine();
  88221. if (physicEngine) {
  88222. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88223. }
  88224. }
  88225. /** @hidden */
  88226. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88227. var plugin = this._physicsEnginePlugin;
  88228. for (var i = 0; i < this._numMeshes; i++) {
  88229. var impostor = this._impostors[i];
  88230. if (!impostor) {
  88231. continue;
  88232. }
  88233. if (impostor.isDisposed) {
  88234. this.hideImpostor(this._impostors[i--]);
  88235. }
  88236. else {
  88237. var mesh = this._meshes[i];
  88238. if (mesh && plugin) {
  88239. plugin.syncMeshWithImpostor(mesh, impostor);
  88240. }
  88241. }
  88242. }
  88243. };
  88244. /**
  88245. * Renders a specified physic impostor
  88246. * @param impostor defines the impostor to render
  88247. */
  88248. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88249. if (!this._scene) {
  88250. return;
  88251. }
  88252. for (var i = 0; i < this._numMeshes; i++) {
  88253. if (this._impostors[i] == impostor) {
  88254. return;
  88255. }
  88256. }
  88257. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88258. if (debugMesh) {
  88259. this._impostors[this._numMeshes] = impostor;
  88260. this._meshes[this._numMeshes] = debugMesh;
  88261. if (this._numMeshes === 0) {
  88262. this._renderFunction = this._updateDebugMeshes.bind(this);
  88263. this._scene.registerBeforeRender(this._renderFunction);
  88264. }
  88265. this._numMeshes++;
  88266. }
  88267. };
  88268. /**
  88269. * Hides a specified physic impostor
  88270. * @param impostor defines the impostor to hide
  88271. */
  88272. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88273. if (!impostor || !this._scene) {
  88274. return;
  88275. }
  88276. var removed = false;
  88277. for (var i = 0; i < this._numMeshes; i++) {
  88278. if (this._impostors[i] == impostor) {
  88279. var mesh = this._meshes[i];
  88280. if (!mesh) {
  88281. continue;
  88282. }
  88283. this._scene.removeMesh(mesh);
  88284. mesh.dispose();
  88285. this._numMeshes--;
  88286. if (this._numMeshes > 0) {
  88287. this._meshes[i] = this._meshes[this._numMeshes];
  88288. this._impostors[i] = this._impostors[this._numMeshes];
  88289. this._meshes[this._numMeshes] = null;
  88290. this._impostors[this._numMeshes] = null;
  88291. }
  88292. else {
  88293. this._meshes[0] = null;
  88294. this._impostors[0] = null;
  88295. }
  88296. removed = true;
  88297. break;
  88298. }
  88299. }
  88300. if (removed && this._numMeshes === 0) {
  88301. this._scene.unregisterBeforeRender(this._renderFunction);
  88302. }
  88303. };
  88304. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88305. if (!this._debugMaterial) {
  88306. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88307. this._debugMaterial.wireframe = true;
  88308. }
  88309. return this._debugMaterial;
  88310. };
  88311. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88312. if (!this._debugBoxMesh) {
  88313. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88314. this._debugBoxMesh.renderingGroupId = 1;
  88315. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88316. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88317. scene.removeMesh(this._debugBoxMesh);
  88318. }
  88319. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88320. };
  88321. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88322. if (!this._debugSphereMesh) {
  88323. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88324. this._debugSphereMesh.renderingGroupId = 1;
  88325. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88326. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88327. scene.removeMesh(this._debugSphereMesh);
  88328. }
  88329. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88330. };
  88331. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88332. var mesh = null;
  88333. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88334. mesh = this._getDebugBoxMesh(scene);
  88335. impostor.getBoxSizeToRef(mesh.scaling);
  88336. }
  88337. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88338. mesh = this._getDebugSphereMesh(scene);
  88339. var radius = impostor.getRadius();
  88340. mesh.scaling.x = radius * 2;
  88341. mesh.scaling.y = radius * 2;
  88342. mesh.scaling.z = radius * 2;
  88343. }
  88344. return mesh;
  88345. };
  88346. /** Releases all resources */
  88347. PhysicsViewer.prototype.dispose = function () {
  88348. for (var i = 0; i < this._numMeshes; i++) {
  88349. this.hideImpostor(this._impostors[i]);
  88350. }
  88351. if (this._debugBoxMesh) {
  88352. this._debugBoxMesh.dispose();
  88353. }
  88354. if (this._debugSphereMesh) {
  88355. this._debugSphereMesh.dispose();
  88356. }
  88357. if (this._debugMaterial) {
  88358. this._debugMaterial.dispose();
  88359. }
  88360. this._impostors.length = 0;
  88361. this._scene = null;
  88362. this._physicsEnginePlugin = null;
  88363. };
  88364. return PhysicsViewer;
  88365. }());
  88366. Debug.PhysicsViewer = PhysicsViewer;
  88367. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88368. })(BABYLON || (BABYLON = {}));
  88369. //# sourceMappingURL=babylon.physicsViewer.js.map
  88370. var BABYLON;
  88371. (function (BABYLON) {
  88372. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  88373. get: function () {
  88374. return this._forceShowBoundingBoxes || false;
  88375. },
  88376. set: function (value) {
  88377. this._forceShowBoundingBoxes = value;
  88378. // Lazyly creates a BB renderer if needed.
  88379. if (value) {
  88380. this.getBoundingBoxRenderer();
  88381. }
  88382. },
  88383. enumerable: true,
  88384. configurable: true
  88385. });
  88386. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  88387. if (!this._boundingBoxRenderer) {
  88388. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  88389. }
  88390. return this._boundingBoxRenderer;
  88391. };
  88392. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  88393. get: function () {
  88394. return this._showBoundingBox || false;
  88395. },
  88396. set: function (value) {
  88397. this._showBoundingBox = value;
  88398. // Lazyly creates a BB renderer if needed.
  88399. if (value) {
  88400. this.getScene().getBoundingBoxRenderer();
  88401. }
  88402. },
  88403. enumerable: true,
  88404. configurable: true
  88405. });
  88406. var BoundingBoxRenderer = /** @class */ (function () {
  88407. function BoundingBoxRenderer(scene) {
  88408. /**
  88409. * The component name helpfull to identify the component in the list of scene components.
  88410. */
  88411. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  88412. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88413. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88414. this.showBackLines = true;
  88415. this.renderList = new BABYLON.SmartArray(32);
  88416. this._vertexBuffers = {};
  88417. this.scene = scene;
  88418. scene._addComponent(this);
  88419. }
  88420. /**
  88421. * Registers the component in a given scene
  88422. */
  88423. BoundingBoxRenderer.prototype.register = function () {
  88424. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  88425. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  88426. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  88427. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  88428. };
  88429. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  88430. if (mesh.showSubMeshesBoundingBox) {
  88431. var boundingInfo = subMesh.getBoundingInfo();
  88432. if (boundingInfo !== null && boundingInfo !== undefined) {
  88433. this.renderList.push(boundingInfo.boundingBox);
  88434. }
  88435. }
  88436. };
  88437. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  88438. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  88439. var boundingInfo = sourceMesh.getBoundingInfo();
  88440. this.renderList.push(boundingInfo.boundingBox);
  88441. }
  88442. };
  88443. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88444. if (this._colorShader) {
  88445. return;
  88446. }
  88447. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  88448. attributes: [BABYLON.VertexBuffer.PositionKind],
  88449. uniforms: ["world", "viewProjection", "color"]
  88450. });
  88451. var engine = this.scene.getEngine();
  88452. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88454. this._createIndexBuffer();
  88455. };
  88456. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88457. var engine = this.scene.getEngine();
  88458. 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]);
  88459. };
  88460. /**
  88461. * Rebuilds the elements related to this component in case of
  88462. * context lost for instance.
  88463. */
  88464. BoundingBoxRenderer.prototype.rebuild = function () {
  88465. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88466. if (vb) {
  88467. vb._rebuild();
  88468. }
  88469. this._createIndexBuffer();
  88470. };
  88471. BoundingBoxRenderer.prototype.reset = function () {
  88472. this.renderList.reset();
  88473. };
  88474. BoundingBoxRenderer.prototype.render = function () {
  88475. if (this.renderList.length === 0) {
  88476. return;
  88477. }
  88478. this._prepareRessources();
  88479. if (!this._colorShader.isReady()) {
  88480. return;
  88481. }
  88482. var engine = this.scene.getEngine();
  88483. engine.setDepthWrite(false);
  88484. this._colorShader._preBind();
  88485. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88486. var boundingBox = this.renderList.data[boundingBoxIndex];
  88487. var min = boundingBox.minimum;
  88488. var max = boundingBox.maximum;
  88489. var diff = max.subtract(min);
  88490. var median = min.add(diff.scale(0.5));
  88491. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88492. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88493. .multiply(boundingBox.getWorldMatrix());
  88494. // VBOs
  88495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88496. if (this.showBackLines) {
  88497. // Back
  88498. engine.setDepthFunctionToGreaterOrEqual();
  88499. this.scene.resetCachedMaterial();
  88500. this._colorShader.setColor4("color", this.backColor.toColor4());
  88501. this._colorShader.bind(worldMatrix);
  88502. // Draw order
  88503. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88504. }
  88505. // Front
  88506. engine.setDepthFunctionToLess();
  88507. this.scene.resetCachedMaterial();
  88508. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88509. this._colorShader.bind(worldMatrix);
  88510. // Draw order
  88511. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88512. }
  88513. this._colorShader.unbind();
  88514. engine.setDepthFunctionToLessOrEqual();
  88515. engine.setDepthWrite(true);
  88516. };
  88517. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88518. this._prepareRessources();
  88519. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88520. return;
  88521. }
  88522. var engine = this.scene.getEngine();
  88523. engine.setDepthWrite(false);
  88524. engine.setColorWrite(false);
  88525. this._colorShader._preBind();
  88526. var boundingBox = mesh._boundingInfo.boundingBox;
  88527. var min = boundingBox.minimum;
  88528. var max = boundingBox.maximum;
  88529. var diff = max.subtract(min);
  88530. var median = min.add(diff.scale(0.5));
  88531. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88532. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88533. .multiply(boundingBox.getWorldMatrix());
  88534. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88535. engine.setDepthFunctionToLess();
  88536. this.scene.resetCachedMaterial();
  88537. this._colorShader.bind(worldMatrix);
  88538. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88539. this._colorShader.unbind();
  88540. engine.setDepthFunctionToLessOrEqual();
  88541. engine.setDepthWrite(true);
  88542. engine.setColorWrite(true);
  88543. };
  88544. BoundingBoxRenderer.prototype.dispose = function () {
  88545. if (!this._colorShader) {
  88546. return;
  88547. }
  88548. this.renderList.dispose();
  88549. this._colorShader.dispose();
  88550. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88551. if (buffer) {
  88552. buffer.dispose();
  88553. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88554. }
  88555. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  88556. };
  88557. return BoundingBoxRenderer;
  88558. }());
  88559. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88560. })(BABYLON || (BABYLON = {}));
  88561. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88562. var BABYLON;
  88563. (function (BABYLON) {
  88564. /**
  88565. * Renders a layer on top of an existing scene
  88566. */
  88567. var UtilityLayerRenderer = /** @class */ (function () {
  88568. /**
  88569. * Instantiates a UtilityLayerRenderer
  88570. * @param originalScene the original scene that will be rendered on top of
  88571. */
  88572. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88573. var _this = this;
  88574. this.originalScene = originalScene;
  88575. this._pointerCaptures = {};
  88576. this._lastPointerEvents = {};
  88577. /**
  88578. * If the utility layer should automatically be rendered on top of existing scene
  88579. */
  88580. this.shouldRender = true;
  88581. /**
  88582. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88583. */
  88584. this.onlyCheckPointerDownEvents = true;
  88585. /**
  88586. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88587. */
  88588. this.processAllEvents = false;
  88589. /**
  88590. * Observable raised when the pointer move from the utility layer scene to the main scene
  88591. */
  88592. this.onPointerOutObservable = new BABYLON.Observable();
  88593. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88594. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88595. originalScene.getEngine().scenes.pop();
  88596. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88597. this.utilityLayerScene.detachControl();
  88598. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88599. if (!_this.processAllEvents) {
  88600. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88601. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88602. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88603. return;
  88604. }
  88605. }
  88606. var pointerEvent = (prePointerInfo.event);
  88607. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88608. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88609. return;
  88610. }
  88611. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88612. if (!prePointerInfo.ray && utilityScenePick) {
  88613. prePointerInfo.ray = utilityScenePick.ray;
  88614. }
  88615. // always fire the prepointer oversvable
  88616. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88617. // allow every non pointer down event to flow to the utility layer
  88618. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88619. if (!prePointerInfo.skipOnPointerObservable) {
  88620. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88621. }
  88622. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88623. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88624. }
  88625. return;
  88626. }
  88627. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88628. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88629. if (utilityScenePick && utilityScenePick.hit) {
  88630. if (!prePointerInfo.skipOnPointerObservable) {
  88631. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88632. }
  88633. prePointerInfo.skipOnPointerObservable = true;
  88634. }
  88635. }
  88636. else {
  88637. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88638. var pointerEvent_1 = (prePointerInfo.event);
  88639. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88640. if (originalScenePick && utilityScenePick) {
  88641. // No pick in utility scene
  88642. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88643. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88644. // We touched an utility mesh present in the main scene
  88645. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88646. prePointerInfo.skipOnPointerObservable = true;
  88647. }
  88648. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88649. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88650. }
  88651. }
  88652. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88653. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88654. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88655. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88656. }
  88657. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88658. // We have a pick in both scenes but main is closer than utility
  88659. // We touched an utility mesh present in the main scene
  88660. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88661. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88662. prePointerInfo.skipOnPointerObservable = true;
  88663. }
  88664. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88665. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88666. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88667. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88668. }
  88669. }
  88670. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88671. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88672. }
  88673. }
  88674. }
  88675. });
  88676. // Render directly on top of existing scene without clearing
  88677. this.utilityLayerScene.autoClear = false;
  88678. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88679. if (_this.shouldRender) {
  88680. _this.render();
  88681. }
  88682. });
  88683. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88684. _this.dispose();
  88685. });
  88686. this._updateCamera();
  88687. }
  88688. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88689. get: function () {
  88690. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88691. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88692. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88693. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88694. });
  88695. }
  88696. return UtilityLayerRenderer._DefaultUtilityLayer;
  88697. },
  88698. enumerable: true,
  88699. configurable: true
  88700. });
  88701. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88702. if (!prePointerInfo.skipOnPointerObservable) {
  88703. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88704. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88705. }
  88706. };
  88707. /**
  88708. * Renders the utility layers scene on top of the original scene
  88709. */
  88710. UtilityLayerRenderer.prototype.render = function () {
  88711. this._updateCamera();
  88712. this.utilityLayerScene.render(false);
  88713. };
  88714. /**
  88715. * Disposes of the renderer
  88716. */
  88717. UtilityLayerRenderer.prototype.dispose = function () {
  88718. this.onPointerOutObservable.clear();
  88719. if (this._afterRenderObserver) {
  88720. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88721. }
  88722. if (this._sceneDisposeObserver) {
  88723. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88724. }
  88725. if (this._originalPointerObserver) {
  88726. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88727. }
  88728. this.utilityLayerScene.dispose();
  88729. };
  88730. UtilityLayerRenderer.prototype._updateCamera = function () {
  88731. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88732. };
  88733. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88734. return UtilityLayerRenderer;
  88735. }());
  88736. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88737. })(BABYLON || (BABYLON = {}));
  88738. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88739. //# sourceMappingURL=babylon.behavior.js.map
  88740. var BABYLON;
  88741. (function (BABYLON) {
  88742. /**
  88743. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88744. */
  88745. var PointerDragBehavior = /** @class */ (function () {
  88746. /**
  88747. * Creates a pointer drag behavior that can be attached to a mesh
  88748. * @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)
  88749. */
  88750. function PointerDragBehavior(options) {
  88751. /**
  88752. * 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)
  88753. */
  88754. this.maxDragAngle = 0;
  88755. /**
  88756. * @hidden
  88757. */
  88758. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88759. /**
  88760. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88761. */
  88762. this.currentDraggingPointerID = -1;
  88763. /**
  88764. * If the behavior is currently in a dragging state
  88765. */
  88766. this.dragging = false;
  88767. /**
  88768. * 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)
  88769. */
  88770. this.dragDeltaRatio = 0.2;
  88771. /**
  88772. * If the drag plane orientation should be updated during the dragging (Default: true)
  88773. */
  88774. this.updateDragPlane = true;
  88775. // Debug mode will display drag planes to help visualize behavior
  88776. this._debugMode = false;
  88777. this._moving = false;
  88778. /**
  88779. * Fires each time the attached mesh is dragged with the pointer
  88780. * * delta between last drag position and current drag position in world space
  88781. * * dragDistance along the drag axis
  88782. * * dragPlaneNormal normal of the current drag plane used during the drag
  88783. * * dragPlanePoint in world space where the drag intersects the drag plane
  88784. */
  88785. this.onDragObservable = new BABYLON.Observable();
  88786. /**
  88787. * Fires each time a drag begins (eg. mouse down on mesh)
  88788. */
  88789. this.onDragStartObservable = new BABYLON.Observable();
  88790. /**
  88791. * Fires each time a drag ends (eg. mouse release after drag)
  88792. */
  88793. this.onDragEndObservable = new BABYLON.Observable();
  88794. /**
  88795. * If the attached mesh should be moved when dragged
  88796. */
  88797. this.moveAttached = true;
  88798. /**
  88799. * If the drag behavior will react to drag events (Default: true)
  88800. */
  88801. this.enabled = true;
  88802. /**
  88803. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88804. */
  88805. this.useObjectOrienationForDragging = true;
  88806. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88807. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88808. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88809. // Variables to avoid instantiation in the below method
  88810. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88811. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88812. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88813. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88814. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88815. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88816. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88817. this._options = options ? options : {};
  88818. var optionCount = 0;
  88819. if (this._options.dragAxis) {
  88820. optionCount++;
  88821. }
  88822. if (this._options.dragPlaneNormal) {
  88823. optionCount++;
  88824. }
  88825. if (optionCount > 1) {
  88826. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88827. }
  88828. }
  88829. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88830. /**
  88831. * The name of the behavior
  88832. */
  88833. get: function () {
  88834. return "PointerDrag";
  88835. },
  88836. enumerable: true,
  88837. configurable: true
  88838. });
  88839. /**
  88840. * Initializes the behavior
  88841. */
  88842. PointerDragBehavior.prototype.init = function () { };
  88843. /**
  88844. * Attaches the drag behavior the passed in mesh
  88845. * @param ownerNode The mesh that will be dragged around once attached
  88846. */
  88847. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88848. var _this = this;
  88849. this._scene = ownerNode.getScene();
  88850. this._attachedNode = ownerNode;
  88851. // Initialize drag plane to not interfere with existing scene
  88852. if (!PointerDragBehavior._planeScene) {
  88853. if (this._debugMode) {
  88854. PointerDragBehavior._planeScene = this._scene;
  88855. }
  88856. else {
  88857. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88858. this._scene.getEngine().scenes.pop();
  88859. }
  88860. }
  88861. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88862. // State of the drag
  88863. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88864. var delta = new BABYLON.Vector3(0, 0, 0);
  88865. var dragLength = 0;
  88866. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88867. var pickPredicate = function (m) {
  88868. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88869. };
  88870. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88871. if (!_this.enabled) {
  88872. return;
  88873. }
  88874. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88875. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88876. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88877. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88878. if (pickedPoint) {
  88879. _this.dragging = true;
  88880. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88881. _this.lastDragPosition.copyFrom(pickedPoint);
  88882. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88883. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88884. }
  88885. }
  88886. }
  88887. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88888. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88889. _this.releaseDrag();
  88890. }
  88891. }
  88892. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88893. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88894. _this._moving = true;
  88895. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88896. if (pickedPoint) {
  88897. if (_this.updateDragPlane) {
  88898. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88899. }
  88900. // depending on the drag mode option drag accordingly
  88901. if (_this._options.dragAxis) {
  88902. // Convert local drag axis to world
  88903. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88904. // Project delta drag from the drag plane onto the drag axis
  88905. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88906. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88907. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88908. }
  88909. else {
  88910. dragLength = delta.length();
  88911. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88912. }
  88913. targetPosition.addInPlace(delta);
  88914. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88915. _this.lastDragPosition.copyFrom(pickedPoint);
  88916. }
  88917. }
  88918. }
  88919. });
  88920. this._scene.onBeforeRenderObservable.add(function () {
  88921. if (_this._moving && _this.moveAttached) {
  88922. // Slowly move mesh to avoid jitter
  88923. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88924. _this._tmpVector.scaleInPlace(0.2);
  88925. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88926. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88927. }
  88928. });
  88929. };
  88930. PointerDragBehavior.prototype.releaseDrag = function () {
  88931. this.dragging = false;
  88932. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88933. this.currentDraggingPointerID = -1;
  88934. this._moving = false;
  88935. };
  88936. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88937. var _this = this;
  88938. if (!ray) {
  88939. return null;
  88940. }
  88941. // Calculate angle between plane normal and ray
  88942. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  88943. // Correct if ray is casted from oposite side
  88944. if (angle > Math.PI / 2) {
  88945. angle = Math.PI - angle;
  88946. }
  88947. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  88948. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  88949. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  88950. // Invert ray direction along the towards object axis
  88951. this._tmpVector.copyFrom(ray.direction);
  88952. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  88953. this._alternatePickedPoint.normalize();
  88954. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  88955. this._tmpVector.addInPlace(this._alternatePickedPoint);
  88956. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  88957. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  88958. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  88959. this._alternatePickedPoint.addInPlace(this._tmpVector);
  88960. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  88961. return this._alternatePickedPoint;
  88962. }
  88963. else {
  88964. return null;
  88965. }
  88966. }
  88967. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88968. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88969. return pickResult.pickedPoint;
  88970. }
  88971. else {
  88972. return null;
  88973. }
  88974. };
  88975. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88976. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88977. this._pointA.copyFrom(dragPlanePosition);
  88978. if (this._options.dragAxis) {
  88979. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  88980. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88981. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88982. ray.origin.subtractToRef(this._pointA, this._pointC);
  88983. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88984. // Get perpendicular line from direction to camera and drag axis
  88985. this._pointB.subtractToRef(this._pointA, this._lineA);
  88986. this._pointC.subtractToRef(this._pointA, this._lineB);
  88987. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88988. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88989. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88990. this._lookAt.normalize();
  88991. this._dragPlane.position.copyFrom(this._pointA);
  88992. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88993. this._dragPlane.lookAt(this._lookAt);
  88994. }
  88995. else if (this._options.dragPlaneNormal) {
  88996. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  88997. this._dragPlane.position.copyFrom(this._pointA);
  88998. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88999. this._dragPlane.lookAt(this._lookAt);
  89000. }
  89001. else {
  89002. this._dragPlane.position.copyFrom(this._pointA);
  89003. this._dragPlane.lookAt(ray.origin);
  89004. }
  89005. this._dragPlane.computeWorldMatrix(true);
  89006. };
  89007. /**
  89008. * Detaches the behavior from the mesh
  89009. */
  89010. PointerDragBehavior.prototype.detach = function () {
  89011. if (this._pointerObserver) {
  89012. this._scene.onPointerObservable.remove(this._pointerObserver);
  89013. }
  89014. };
  89015. return PointerDragBehavior;
  89016. }());
  89017. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89018. })(BABYLON || (BABYLON = {}));
  89019. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89020. var BABYLON;
  89021. (function (BABYLON) {
  89022. /**
  89023. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89024. */
  89025. var MultiPointerScaleBehavior = /** @class */ (function () {
  89026. function MultiPointerScaleBehavior() {
  89027. this._startDistance = 0;
  89028. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89029. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89030. this._sceneRenderObserver = null;
  89031. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89032. this._dragBehaviorA.moveAttached = false;
  89033. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89034. this._dragBehaviorB.moveAttached = false;
  89035. }
  89036. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89037. /**
  89038. * The name of the behavior
  89039. */
  89040. get: function () {
  89041. return "MultiPointerScale";
  89042. },
  89043. enumerable: true,
  89044. configurable: true
  89045. });
  89046. /**
  89047. * Initializes the behavior
  89048. */
  89049. MultiPointerScaleBehavior.prototype.init = function () { };
  89050. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89051. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89052. };
  89053. /**
  89054. * Attaches the scale behavior the passed in mesh
  89055. * @param ownerNode The mesh that will be scaled around once attached
  89056. */
  89057. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89058. var _this = this;
  89059. this._ownerNode = ownerNode;
  89060. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89061. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89062. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89063. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89064. _this._dragBehaviorA.releaseDrag();
  89065. }
  89066. else {
  89067. _this._initialScale.copyFrom(ownerNode.scaling);
  89068. _this._startDistance = _this._getCurrentDistance();
  89069. }
  89070. }
  89071. });
  89072. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89073. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89074. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89075. _this._dragBehaviorB.releaseDrag();
  89076. }
  89077. else {
  89078. _this._initialScale.copyFrom(ownerNode.scaling);
  89079. _this._startDistance = _this._getCurrentDistance();
  89080. }
  89081. }
  89082. });
  89083. // Once both drag behaviors are active scale based on the distance between the two pointers
  89084. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89085. behavior.onDragObservable.add(function () {
  89086. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89087. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89088. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89089. }
  89090. });
  89091. });
  89092. ownerNode.addBehavior(this._dragBehaviorA);
  89093. ownerNode.addBehavior(this._dragBehaviorB);
  89094. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89095. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89096. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89097. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89098. if (change.length() > 0.01) {
  89099. ownerNode.scaling.addInPlace(change);
  89100. }
  89101. }
  89102. });
  89103. };
  89104. /**
  89105. * Detaches the behavior from the mesh
  89106. */
  89107. MultiPointerScaleBehavior.prototype.detach = function () {
  89108. var _this = this;
  89109. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89110. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89111. behavior.onDragStartObservable.clear();
  89112. behavior.onDragObservable.clear();
  89113. _this._ownerNode.removeBehavior(behavior);
  89114. });
  89115. };
  89116. return MultiPointerScaleBehavior;
  89117. }());
  89118. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89119. })(BABYLON || (BABYLON = {}));
  89120. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89121. var BABYLON;
  89122. (function (BABYLON) {
  89123. /**
  89124. * 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
  89125. */
  89126. var SixDofDragBehavior = /** @class */ (function () {
  89127. function SixDofDragBehavior() {
  89128. this._sceneRenderObserver = null;
  89129. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89130. this._moving = false;
  89131. this._startingOrientation = new BABYLON.Quaternion();
  89132. /**
  89133. * 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)
  89134. */
  89135. this.zDragFactor = 3;
  89136. /**
  89137. * If the behavior is currently in a dragging state
  89138. */
  89139. this.dragging = false;
  89140. /**
  89141. * 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)
  89142. */
  89143. this.dragDeltaRatio = 0.2;
  89144. /**
  89145. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89146. */
  89147. this.currentDraggingPointerID = -1;
  89148. }
  89149. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89150. /**
  89151. * The name of the behavior
  89152. */
  89153. get: function () {
  89154. return "SixDofDrag";
  89155. },
  89156. enumerable: true,
  89157. configurable: true
  89158. });
  89159. /**
  89160. * Initializes the behavior
  89161. */
  89162. SixDofDragBehavior.prototype.init = function () { };
  89163. /**
  89164. * Attaches the scale behavior the passed in mesh
  89165. * @param ownerNode The mesh that will be scaled around once attached
  89166. */
  89167. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89168. var _this = this;
  89169. this._ownerNode = ownerNode;
  89170. this._scene = this._ownerNode.getScene();
  89171. if (!SixDofDragBehavior._virtualScene) {
  89172. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89173. this._scene.getEngine().scenes.pop();
  89174. }
  89175. var pickedMesh = null;
  89176. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89177. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89178. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89179. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89180. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89181. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89182. var pickPredicate = function (m) {
  89183. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89184. };
  89185. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89186. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89187. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89188. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89189. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89190. }
  89191. pickedMesh = _this._ownerNode;
  89192. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89193. // Set position and orientation of the controller
  89194. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89195. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89196. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89197. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89198. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89199. if (!pickedMesh.rotationQuaternion) {
  89200. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89201. }
  89202. var oldParent = pickedMesh.parent;
  89203. pickedMesh.setParent(null);
  89204. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89205. pickedMesh.setParent(oldParent);
  89206. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89207. // Update state
  89208. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89209. _this.dragging = true;
  89210. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89211. }
  89212. }
  89213. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89214. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89215. _this.dragging = false;
  89216. _this._moving = false;
  89217. _this.currentDraggingPointerID = -1;
  89218. pickedMesh = null;
  89219. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89220. }
  89221. }
  89222. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89223. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89224. var zDragFactor = _this.zDragFactor;
  89225. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89226. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89227. zDragFactor = 0;
  89228. }
  89229. // Calculate controller drag distance in controller space
  89230. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89231. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89232. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89233. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89234. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89235. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89236. if (_this._virtualDragMesh.position.z < 0) {
  89237. _this._virtualDragMesh.position.z = 0;
  89238. }
  89239. // Update the controller position
  89240. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89241. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89242. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89243. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89244. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89245. if (pickedMesh.parent) {
  89246. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89247. }
  89248. if (!_this._moving) {
  89249. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89250. }
  89251. _this._moving = true;
  89252. }
  89253. }
  89254. });
  89255. var tmpQuaternion = new BABYLON.Quaternion();
  89256. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89257. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89258. if (_this.dragging && _this._moving && pickedMesh) {
  89259. // Slowly move mesh to avoid jitter
  89260. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89261. // Get change in rotation
  89262. tmpQuaternion.copyFrom(_this._startingOrientation);
  89263. tmpQuaternion.x = -tmpQuaternion.x;
  89264. tmpQuaternion.y = -tmpQuaternion.y;
  89265. tmpQuaternion.z = -tmpQuaternion.z;
  89266. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89267. // Convert change in rotation to only y axis rotation
  89268. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89269. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89270. // Slowly move mesh to avoid jitter
  89271. var oldParent = pickedMesh.parent;
  89272. pickedMesh.setParent(null);
  89273. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89274. pickedMesh.setParent(oldParent);
  89275. }
  89276. });
  89277. };
  89278. /**
  89279. * Detaches the behavior from the mesh
  89280. */
  89281. SixDofDragBehavior.prototype.detach = function () {
  89282. if (this._scene) {
  89283. this._scene.onPointerObservable.remove(this._pointerObserver);
  89284. }
  89285. if (this._ownerNode) {
  89286. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89287. }
  89288. if (this._virtualOriginMesh) {
  89289. this._virtualOriginMesh.dispose();
  89290. }
  89291. if (this._virtualDragMesh) {
  89292. this._virtualDragMesh.dispose();
  89293. }
  89294. };
  89295. return SixDofDragBehavior;
  89296. }());
  89297. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89298. })(BABYLON || (BABYLON = {}));
  89299. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89300. var BABYLON;
  89301. (function (BABYLON) {
  89302. /**
  89303. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89304. */
  89305. var Gizmo = /** @class */ (function () {
  89306. /**
  89307. * Creates a gizmo
  89308. * @param gizmoLayer The utility layer the gizmo will be added to
  89309. */
  89310. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89311. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89312. var _this = this;
  89313. this.gizmoLayer = gizmoLayer;
  89314. this._scaleFactor = 3;
  89315. this._tmpMatrix = new BABYLON.Matrix();
  89316. /**
  89317. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89318. */
  89319. this.updateGizmoRotationToMatchAttachedMesh = true;
  89320. /**
  89321. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89322. */
  89323. this.updateGizmoPositionToMatchAttachedMesh = true;
  89324. /**
  89325. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89326. */
  89327. this._updateScale = true;
  89328. this._interactionsEnabled = true;
  89329. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89330. var tempVector = new BABYLON.Vector3();
  89331. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89332. if (_this.attachedMesh) {
  89333. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89334. if (!_this._rootMesh.rotationQuaternion) {
  89335. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89336. }
  89337. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89338. tempVector.copyFrom(_this.attachedMesh.scaling);
  89339. if (_this.attachedMesh.scaling.x < 0) {
  89340. _this.attachedMesh.scaling.x *= -1;
  89341. }
  89342. if (_this.attachedMesh.scaling.y < 0) {
  89343. _this.attachedMesh.scaling.y *= -1;
  89344. }
  89345. if (_this.attachedMesh.scaling.z < 0) {
  89346. _this.attachedMesh.scaling.z *= -1;
  89347. }
  89348. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89349. _this.attachedMesh.scaling.copyFrom(tempVector);
  89350. _this.attachedMesh.computeWorldMatrix();
  89351. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89352. }
  89353. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89354. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89355. }
  89356. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89357. var cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.position;
  89358. if (_this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  89359. cameraPosition = _this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  89360. }
  89361. _this._rootMesh.position.subtractToRef(cameraPosition, tempVector);
  89362. var dist = tempVector.length() / _this._scaleFactor;
  89363. _this._rootMesh.scaling.set(dist, dist, dist);
  89364. }
  89365. }
  89366. });
  89367. this.attachedMesh = null;
  89368. }
  89369. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89370. /**
  89371. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89372. * * When set, interactions will be enabled
  89373. */
  89374. get: function () {
  89375. return this._attachedMesh;
  89376. },
  89377. set: function (value) {
  89378. this._attachedMesh = value;
  89379. this._rootMesh.setEnabled(value ? true : false);
  89380. this._attachedMeshChanged(value);
  89381. },
  89382. enumerable: true,
  89383. configurable: true
  89384. });
  89385. Gizmo.prototype._attachedMeshChanged = function (value) {
  89386. };
  89387. /**
  89388. * Disposes of the gizmo
  89389. */
  89390. Gizmo.prototype.dispose = function () {
  89391. this._rootMesh.dispose();
  89392. if (this._beforeRenderObserver) {
  89393. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89394. }
  89395. };
  89396. return Gizmo;
  89397. }());
  89398. BABYLON.Gizmo = Gizmo;
  89399. })(BABYLON || (BABYLON = {}));
  89400. //# sourceMappingURL=babylon.gizmo.js.map
  89401. var BABYLON;
  89402. (function (BABYLON) {
  89403. /**
  89404. * Single axis drag gizmo
  89405. */
  89406. var AxisDragGizmo = /** @class */ (function (_super) {
  89407. __extends(AxisDragGizmo, _super);
  89408. /**
  89409. * Creates an AxisDragGizmo
  89410. * @param gizmoLayer The utility layer the gizmo will be added to
  89411. * @param dragAxis The axis which the gizmo will be able to drag on
  89412. * @param color The color of the gizmo
  89413. */
  89414. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89415. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89416. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89417. var _this = _super.call(this, gizmoLayer) || this;
  89418. _this._pointerObserver = null;
  89419. /**
  89420. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89421. */
  89422. _this.snapDistance = 0;
  89423. /**
  89424. * Event that fires each time the gizmo snaps to a new location.
  89425. * * snapDistance is the the change in distance
  89426. */
  89427. _this.onSnapObservable = new BABYLON.Observable();
  89428. // Create Material
  89429. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89430. coloredMaterial.disableLighting = true;
  89431. coloredMaterial.emissiveColor = color;
  89432. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89433. hoverMaterial.disableLighting = true;
  89434. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89435. // Build mesh on root node
  89436. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89437. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89438. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89439. arrow.addChild(arrowMesh);
  89440. arrow.addChild(arrowTail);
  89441. // Position arrow pointing in its drag axis
  89442. arrowMesh.scaling.scaleInPlace(0.05);
  89443. arrowMesh.material = coloredMaterial;
  89444. arrowMesh.rotation.x = Math.PI / 2;
  89445. arrowMesh.position.z += 0.3;
  89446. arrowTail.rotation.x = Math.PI / 2;
  89447. arrowTail.material = coloredMaterial;
  89448. arrowTail.position.z += 0.15;
  89449. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89450. _this._rootMesh.addChild(arrow);
  89451. var currentSnapDragDistance = 0;
  89452. var tmpVector = new BABYLON.Vector3();
  89453. var tmpSnapEvent = { snapDistance: 0 };
  89454. // Add drag behavior to handle events when the gizmo is dragged
  89455. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89456. _this.dragBehavior.moveAttached = false;
  89457. _this._rootMesh.addBehavior(_this.dragBehavior);
  89458. _this.dragBehavior.onDragObservable.add(function (event) {
  89459. if (_this.attachedMesh) {
  89460. // Snapping logic
  89461. if (_this.snapDistance == 0) {
  89462. _this.attachedMesh.position.addInPlace(event.delta);
  89463. }
  89464. else {
  89465. currentSnapDragDistance += event.dragDistance;
  89466. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89467. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89468. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89469. event.delta.normalizeToRef(tmpVector);
  89470. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89471. _this.attachedMesh.position.addInPlace(tmpVector);
  89472. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89473. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89474. }
  89475. }
  89476. }
  89477. });
  89478. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89479. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89480. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89481. m.material = hoverMaterial;
  89482. });
  89483. }
  89484. else {
  89485. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89486. m.material = coloredMaterial;
  89487. });
  89488. }
  89489. });
  89490. return _this;
  89491. }
  89492. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89493. if (this.dragBehavior) {
  89494. this.dragBehavior.enabled = value ? true : false;
  89495. }
  89496. };
  89497. /**
  89498. * Disposes of the gizmo
  89499. */
  89500. AxisDragGizmo.prototype.dispose = function () {
  89501. this.onSnapObservable.clear();
  89502. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89503. this.dragBehavior.detach();
  89504. _super.prototype.dispose.call(this);
  89505. };
  89506. return AxisDragGizmo;
  89507. }(BABYLON.Gizmo));
  89508. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89509. })(BABYLON || (BABYLON = {}));
  89510. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89511. var BABYLON;
  89512. (function (BABYLON) {
  89513. /**
  89514. * Single axis scale gizmo
  89515. */
  89516. var AxisScaleGizmo = /** @class */ (function (_super) {
  89517. __extends(AxisScaleGizmo, _super);
  89518. /**
  89519. * Creates an AxisScaleGizmo
  89520. * @param gizmoLayer The utility layer the gizmo will be added to
  89521. * @param dragAxis The axis which the gizmo will be able to scale on
  89522. * @param color The color of the gizmo
  89523. */
  89524. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89525. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89526. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89527. var _this = _super.call(this, gizmoLayer) || this;
  89528. _this._pointerObserver = null;
  89529. /**
  89530. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89531. */
  89532. _this.snapDistance = 0;
  89533. /**
  89534. * Event that fires each time the gizmo snaps to a new location.
  89535. * * snapDistance is the the change in distance
  89536. */
  89537. _this.onSnapObservable = new BABYLON.Observable();
  89538. // Create Material
  89539. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89540. coloredMaterial.disableLighting = true;
  89541. coloredMaterial.emissiveColor = color;
  89542. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89543. hoverMaterial.disableLighting = true;
  89544. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89545. // Build mesh on root node
  89546. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89547. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89548. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89549. arrow.addChild(arrowMesh);
  89550. arrow.addChild(arrowTail);
  89551. // Position arrow pointing in its drag axis
  89552. arrowMesh.scaling.scaleInPlace(0.1);
  89553. arrowMesh.material = coloredMaterial;
  89554. arrowMesh.rotation.x = Math.PI / 2;
  89555. arrowMesh.position.z += 0.3;
  89556. arrowTail.rotation.x = Math.PI / 2;
  89557. arrowTail.material = coloredMaterial;
  89558. arrowTail.position.z += 0.15;
  89559. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89560. _this._rootMesh.addChild(arrow);
  89561. // Add drag behavior to handle events when the gizmo is dragged
  89562. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89563. _this.dragBehavior.moveAttached = false;
  89564. _this._rootMesh.addBehavior(_this.dragBehavior);
  89565. var currentSnapDragDistance = 0;
  89566. var tmpVector = new BABYLON.Vector3();
  89567. var tmpSnapEvent = { snapDistance: 0 };
  89568. _this.dragBehavior.onDragObservable.add(function (event) {
  89569. if (_this.attachedMesh) {
  89570. // Snapping logic
  89571. var snapped = false;
  89572. var dragSteps = 0;
  89573. if (_this.snapDistance == 0) {
  89574. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89575. }
  89576. else {
  89577. currentSnapDragDistance += event.dragDistance;
  89578. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89579. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89580. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89581. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89582. snapped = true;
  89583. }
  89584. else {
  89585. tmpVector.scaleInPlace(0);
  89586. }
  89587. }
  89588. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89589. if (snapped) {
  89590. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89591. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89592. }
  89593. }
  89594. });
  89595. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89596. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89597. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89598. m.material = hoverMaterial;
  89599. });
  89600. }
  89601. else {
  89602. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89603. m.material = coloredMaterial;
  89604. });
  89605. }
  89606. });
  89607. return _this;
  89608. }
  89609. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89610. if (this.dragBehavior) {
  89611. this.dragBehavior.enabled = value ? true : false;
  89612. }
  89613. };
  89614. /**
  89615. * Disposes of the gizmo
  89616. */
  89617. AxisScaleGizmo.prototype.dispose = function () {
  89618. this.onSnapObservable.clear();
  89619. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89620. this.dragBehavior.detach();
  89621. _super.prototype.dispose.call(this);
  89622. };
  89623. return AxisScaleGizmo;
  89624. }(BABYLON.Gizmo));
  89625. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89626. })(BABYLON || (BABYLON = {}));
  89627. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89628. var BABYLON;
  89629. (function (BABYLON) {
  89630. /**
  89631. * Single plane rotation gizmo
  89632. */
  89633. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89634. __extends(PlaneRotationGizmo, _super);
  89635. /**
  89636. * Creates a PlaneRotationGizmo
  89637. * @param gizmoLayer The utility layer the gizmo will be added to
  89638. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89639. * @param color The color of the gizmo
  89640. */
  89641. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89642. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89643. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89644. var _this = _super.call(this, gizmoLayer) || this;
  89645. _this._pointerObserver = null;
  89646. /**
  89647. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89648. */
  89649. _this.snapDistance = 0;
  89650. /**
  89651. * Event that fires each time the gizmo snaps to a new location.
  89652. * * snapDistance is the the change in distance
  89653. */
  89654. _this.onSnapObservable = new BABYLON.Observable();
  89655. // Create Material
  89656. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89657. coloredMaterial.disableLighting = true;
  89658. coloredMaterial.emissiveColor = color;
  89659. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89660. hoverMaterial.disableLighting = true;
  89661. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89662. // Build mesh on root node
  89663. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89664. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89665. // Position arrow pointing in its drag axis
  89666. rotationMesh.scaling.scaleInPlace(0.1);
  89667. rotationMesh.material = coloredMaterial;
  89668. rotationMesh.rotation.x = Math.PI / 2;
  89669. parentMesh.addChild(rotationMesh);
  89670. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89671. _this._rootMesh.addChild(parentMesh);
  89672. // Add drag behavior to handle events when the gizmo is dragged
  89673. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89674. _this.dragBehavior.moveAttached = false;
  89675. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89676. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89677. _this._rootMesh.addBehavior(_this.dragBehavior);
  89678. var lastDragPosition = new BABYLON.Vector3();
  89679. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89680. if (_this.attachedMesh) {
  89681. lastDragPosition.copyFrom(e.dragPlanePoint);
  89682. }
  89683. });
  89684. var rotationMatrix = new BABYLON.Matrix();
  89685. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89686. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89687. var tmpSnapEvent = { snapDistance: 0 };
  89688. var currentSnapDragDistance = 0;
  89689. _this.dragBehavior.onDragObservable.add(function (event) {
  89690. if (_this.attachedMesh) {
  89691. if (!_this.attachedMesh.rotationQuaternion) {
  89692. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89693. }
  89694. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89695. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89696. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89697. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89698. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89699. var angle = Math.atan2(cross.length(), dot);
  89700. planeNormalTowardsCamera.copyFrom(planeNormal);
  89701. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89702. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89703. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89704. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89705. }
  89706. // Flip up vector depending on which side the camera is on
  89707. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89708. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89709. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89710. planeNormalTowardsCamera.scaleInPlace(-1);
  89711. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89712. }
  89713. }
  89714. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89715. if (halfCircleSide)
  89716. angle = -angle;
  89717. // Snapping logic
  89718. var snapped = false;
  89719. if (_this.snapDistance != 0) {
  89720. currentSnapDragDistance += angle;
  89721. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89722. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89723. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89724. angle = _this.snapDistance * dragSteps;
  89725. snapped = true;
  89726. }
  89727. else {
  89728. angle = 0;
  89729. }
  89730. }
  89731. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89732. var quaternionCoefficient = Math.sin(angle / 2);
  89733. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89734. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89735. // Rotate selected mesh quaternion over fixed axis
  89736. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89737. }
  89738. else {
  89739. // Rotate selected mesh quaternion over rotated axis
  89740. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89741. }
  89742. lastDragPosition.copyFrom(event.dragPlanePoint);
  89743. if (snapped) {
  89744. tmpSnapEvent.snapDistance = angle;
  89745. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89746. }
  89747. }
  89748. });
  89749. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89750. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89751. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89752. m.material = hoverMaterial;
  89753. });
  89754. }
  89755. else {
  89756. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89757. m.material = coloredMaterial;
  89758. });
  89759. }
  89760. });
  89761. return _this;
  89762. }
  89763. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89764. if (this.dragBehavior) {
  89765. this.dragBehavior.enabled = value ? true : false;
  89766. }
  89767. };
  89768. /**
  89769. * Disposes of the gizmo
  89770. */
  89771. PlaneRotationGizmo.prototype.dispose = function () {
  89772. this.onSnapObservable.clear();
  89773. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89774. this.dragBehavior.detach();
  89775. _super.prototype.dispose.call(this);
  89776. };
  89777. return PlaneRotationGizmo;
  89778. }(BABYLON.Gizmo));
  89779. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89780. })(BABYLON || (BABYLON = {}));
  89781. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89782. var BABYLON;
  89783. (function (BABYLON) {
  89784. /**
  89785. * Gizmo that enables dragging a mesh along 3 axis
  89786. */
  89787. var PositionGizmo = /** @class */ (function (_super) {
  89788. __extends(PositionGizmo, _super);
  89789. /**
  89790. * Creates a PositionGizmo
  89791. * @param gizmoLayer The utility layer the gizmo will be added to
  89792. */
  89793. function PositionGizmo(gizmoLayer) {
  89794. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89795. var _this = _super.call(this, gizmoLayer) || this;
  89796. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89797. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89798. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89799. _this.attachedMesh = null;
  89800. return _this;
  89801. }
  89802. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89803. set: function (mesh) {
  89804. if (this.xGizmo) {
  89805. this.xGizmo.attachedMesh = mesh;
  89806. this.yGizmo.attachedMesh = mesh;
  89807. this.zGizmo.attachedMesh = mesh;
  89808. }
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89814. get: function () {
  89815. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89816. },
  89817. set: function (value) {
  89818. if (this.xGizmo) {
  89819. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89820. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89821. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89822. }
  89823. },
  89824. enumerable: true,
  89825. configurable: true
  89826. });
  89827. /**
  89828. * Disposes of the gizmo
  89829. */
  89830. PositionGizmo.prototype.dispose = function () {
  89831. this.xGizmo.dispose();
  89832. this.yGizmo.dispose();
  89833. this.zGizmo.dispose();
  89834. };
  89835. return PositionGizmo;
  89836. }(BABYLON.Gizmo));
  89837. BABYLON.PositionGizmo = PositionGizmo;
  89838. })(BABYLON || (BABYLON = {}));
  89839. //# sourceMappingURL=babylon.positionGizmo.js.map
  89840. var BABYLON;
  89841. (function (BABYLON) {
  89842. /**
  89843. * Gizmo that enables rotating a mesh along 3 axis
  89844. */
  89845. var RotationGizmo = /** @class */ (function (_super) {
  89846. __extends(RotationGizmo, _super);
  89847. /**
  89848. * Creates a RotationGizmo
  89849. * @param gizmoLayer The utility layer the gizmo will be added to
  89850. */
  89851. function RotationGizmo(gizmoLayer) {
  89852. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89853. var _this = _super.call(this, gizmoLayer) || this;
  89854. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89855. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89856. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89857. _this.attachedMesh = null;
  89858. return _this;
  89859. }
  89860. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89861. set: function (mesh) {
  89862. if (this.xGizmo) {
  89863. this.xGizmo.attachedMesh = mesh;
  89864. this.yGizmo.attachedMesh = mesh;
  89865. this.zGizmo.attachedMesh = mesh;
  89866. }
  89867. },
  89868. enumerable: true,
  89869. configurable: true
  89870. });
  89871. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89872. get: function () {
  89873. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89874. },
  89875. set: function (value) {
  89876. if (this.xGizmo) {
  89877. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89878. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89879. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89880. }
  89881. },
  89882. enumerable: true,
  89883. configurable: true
  89884. });
  89885. /**
  89886. * Disposes of the gizmo
  89887. */
  89888. RotationGizmo.prototype.dispose = function () {
  89889. this.xGizmo.dispose();
  89890. this.yGizmo.dispose();
  89891. this.zGizmo.dispose();
  89892. };
  89893. return RotationGizmo;
  89894. }(BABYLON.Gizmo));
  89895. BABYLON.RotationGizmo = RotationGizmo;
  89896. })(BABYLON || (BABYLON = {}));
  89897. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89898. var BABYLON;
  89899. (function (BABYLON) {
  89900. /**
  89901. * Gizmo that enables scaling a mesh along 3 axis
  89902. */
  89903. var ScaleGizmo = /** @class */ (function (_super) {
  89904. __extends(ScaleGizmo, _super);
  89905. /**
  89906. * Creates a ScaleGizmo
  89907. * @param gizmoLayer The utility layer the gizmo will be added to
  89908. */
  89909. function ScaleGizmo(gizmoLayer) {
  89910. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89911. var _this = _super.call(this, gizmoLayer) || this;
  89912. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89913. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89914. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89915. _this.attachedMesh = null;
  89916. return _this;
  89917. }
  89918. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89919. set: function (mesh) {
  89920. if (this.xGizmo) {
  89921. this.xGizmo.attachedMesh = mesh;
  89922. this.yGizmo.attachedMesh = mesh;
  89923. this.zGizmo.attachedMesh = mesh;
  89924. }
  89925. },
  89926. enumerable: true,
  89927. configurable: true
  89928. });
  89929. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89930. get: function () {
  89931. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89932. },
  89933. set: function (value) {
  89934. if (this.xGizmo) {
  89935. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89936. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89937. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89938. }
  89939. },
  89940. enumerable: true,
  89941. configurable: true
  89942. });
  89943. /**
  89944. * Disposes of the gizmo
  89945. */
  89946. ScaleGizmo.prototype.dispose = function () {
  89947. this.xGizmo.dispose();
  89948. this.yGizmo.dispose();
  89949. this.zGizmo.dispose();
  89950. };
  89951. return ScaleGizmo;
  89952. }(BABYLON.Gizmo));
  89953. BABYLON.ScaleGizmo = ScaleGizmo;
  89954. })(BABYLON || (BABYLON = {}));
  89955. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89956. var BABYLON;
  89957. (function (BABYLON) {
  89958. /**
  89959. * Bounding box gizmo
  89960. */
  89961. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89962. __extends(BoundingBoxGizmo, _super);
  89963. /**
  89964. * Creates an BoundingBoxGizmo
  89965. * @param gizmoLayer The utility layer the gizmo will be added to
  89966. * @param color The color of the gizmo
  89967. */
  89968. function BoundingBoxGizmo(color, gizmoLayer) {
  89969. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89970. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89971. var _this = _super.call(this, gizmoLayer) || this;
  89972. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89973. _this._renderObserver = null;
  89974. _this._pointerObserver = null;
  89975. _this._scaleDragSpeed = 0.2;
  89976. _this._tmpQuaternion = new BABYLON.Quaternion();
  89977. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89978. /**
  89979. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89980. */
  89981. _this.rotationSphereSize = 0.1;
  89982. /**
  89983. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89984. */
  89985. _this.scaleBoxSize = 0.1;
  89986. /**
  89987. * 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)
  89988. */
  89989. _this.fixedDragMeshScreenSize = false;
  89990. /**
  89991. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89992. */
  89993. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89994. /**
  89995. * Fired when a rotation sphere or scale box is dragged
  89996. */
  89997. _this.onDragStartObservable = new BABYLON.Observable();
  89998. /**
  89999. * Fired when a rotation sphere or scale box drag is started
  90000. */
  90001. _this.onDragObservable = new BABYLON.Observable();
  90002. /**
  90003. * Fired when a rotation sphere or scale box drag is needed
  90004. */
  90005. _this.onDragEndObservable = new BABYLON.Observable();
  90006. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90007. _this._updateScale = false;
  90008. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90009. // Create Materials
  90010. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90011. coloredMaterial.disableLighting = true;
  90012. coloredMaterial.emissiveColor = color;
  90013. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90014. hoverColoredMaterial.disableLighting = true;
  90015. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90016. // Build bounding box out of lines
  90017. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90018. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90019. var lines = [];
  90020. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90021. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90022. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90023. 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));
  90024. 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));
  90025. 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));
  90026. 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));
  90027. 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));
  90028. 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));
  90029. 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));
  90030. 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));
  90031. 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));
  90032. lines.forEach(function (l) {
  90033. l.color = color;
  90034. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90035. l.isPickable = false;
  90036. _this._lineBoundingBox.addChild(l);
  90037. });
  90038. _this._rootMesh.addChild(_this._lineBoundingBox);
  90039. // Create rotation spheres
  90040. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90041. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90042. var _loop_1 = function (i_1) {
  90043. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90044. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90045. sphere.material = coloredMaterial;
  90046. // Drag behavior
  90047. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90048. _dragBehavior.moveAttached = false;
  90049. _dragBehavior.updateDragPlane = false;
  90050. sphere.addBehavior(_dragBehavior);
  90051. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90052. var totalTurnAmountOfDrag = 0;
  90053. _dragBehavior.onDragStartObservable.add(function (event) {
  90054. startingTurnDirection.copyFrom(sphere.forward);
  90055. totalTurnAmountOfDrag = 0;
  90056. });
  90057. _dragBehavior.onDragObservable.add(function (event) {
  90058. _this.onDragObservable.notifyObservers({});
  90059. if (_this.attachedMesh) {
  90060. var worldDragDirection = startingTurnDirection;
  90061. // Project the world right on to the drag plane
  90062. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90063. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90064. // project drag delta on to the resulting drag axis and rotate based on that
  90065. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90066. // Rotate based on axis
  90067. if (!_this.attachedMesh.rotationQuaternion) {
  90068. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90069. }
  90070. if (!_this._anchorMesh.rotationQuaternion) {
  90071. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90072. }
  90073. // Do not allow the object to turn more than a full circle
  90074. totalTurnAmountOfDrag += projectDist;
  90075. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90076. if (i_1 >= 8) {
  90077. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90078. }
  90079. else if (i_1 >= 4) {
  90080. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90081. }
  90082. else {
  90083. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90084. }
  90085. // Rotate around center of bounding box
  90086. _this._anchorMesh.addChild(_this.attachedMesh);
  90087. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90088. _this._anchorMesh.removeChild(_this.attachedMesh);
  90089. }
  90090. }
  90091. });
  90092. // Selection/deselection
  90093. _dragBehavior.onDragStartObservable.add(function () {
  90094. _this.onDragStartObservable.notifyObservers({});
  90095. _this._selectNode(sphere);
  90096. });
  90097. _dragBehavior.onDragEndObservable.add(function () {
  90098. _this.onDragEndObservable.notifyObservers({});
  90099. _this._selectNode(null);
  90100. });
  90101. this_1._rotateSpheresParent.addChild(sphere);
  90102. };
  90103. var this_1 = this, _dragBehavior;
  90104. for (var i_1 = 0; i_1 < 12; i_1++) {
  90105. _loop_1(i_1);
  90106. }
  90107. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90108. // Create scale cubes
  90109. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90110. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90111. for (var i = 0; i < 2; i++) {
  90112. for (var j = 0; j < 2; j++) {
  90113. var _loop_2 = function () {
  90114. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90115. box.material = coloredMaterial;
  90116. // Dragging logic
  90117. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90118. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90119. _dragBehavior.moveAttached = false;
  90120. box.addBehavior(_dragBehavior);
  90121. _dragBehavior.onDragObservable.add(function (event) {
  90122. _this.onDragObservable.notifyObservers({});
  90123. if (_this.attachedMesh) {
  90124. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90125. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90126. _this._updateBoundingBox();
  90127. // Scale from the position of the opposite corner
  90128. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90129. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90130. _this._anchorMesh.addChild(_this.attachedMesh);
  90131. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90132. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90133. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90134. }
  90135. _this._anchorMesh.removeChild(_this.attachedMesh);
  90136. }
  90137. });
  90138. // Selection/deselection
  90139. _dragBehavior.onDragStartObservable.add(function () {
  90140. _this.onDragStartObservable.notifyObservers({});
  90141. _this._selectNode(box);
  90142. });
  90143. _dragBehavior.onDragEndObservable.add(function () {
  90144. _this.onDragEndObservable.notifyObservers({});
  90145. _this._selectNode(null);
  90146. });
  90147. this_2._scaleBoxesParent.addChild(box);
  90148. };
  90149. var this_2 = this, _dragBehavior;
  90150. for (var k = 0; k < 2; k++) {
  90151. _loop_2();
  90152. }
  90153. }
  90154. }
  90155. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90156. // Hover color change
  90157. var pointerIds = new Array();
  90158. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90159. if (!pointerIds[pointerInfo.event.pointerId]) {
  90160. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90161. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90162. pointerIds[pointerInfo.event.pointerId] = mesh;
  90163. mesh.material = hoverColoredMaterial;
  90164. }
  90165. });
  90166. }
  90167. else {
  90168. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90169. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90170. delete pointerIds[pointerInfo.event.pointerId];
  90171. }
  90172. }
  90173. });
  90174. // Update bounding box positions
  90175. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90176. _this._updateBoundingBox();
  90177. });
  90178. _this._updateBoundingBox();
  90179. return _this;
  90180. }
  90181. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90182. if (value) {
  90183. // Reset anchor mesh to match attached mesh's scale
  90184. // This is needed to avoid invalid box/sphere position on first drag
  90185. this._anchorMesh.addChild(value);
  90186. this._anchorMesh.removeChild(value);
  90187. this._updateBoundingBox();
  90188. }
  90189. };
  90190. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90191. this._rotateSpheresParent.getChildMeshes()
  90192. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90193. m.isVisible = (!selectedMesh || m == selectedMesh);
  90194. });
  90195. };
  90196. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90197. var _this = this;
  90198. mesh.computeWorldMatrix(true);
  90199. mesh.getChildMeshes().forEach(function (m) {
  90200. _this._recurseComputeWorld(m);
  90201. });
  90202. };
  90203. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90204. if (this.attachedMesh) {
  90205. // Rotate based on axis
  90206. if (!this.attachedMesh.rotationQuaternion) {
  90207. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90208. }
  90209. if (!this._anchorMesh.rotationQuaternion) {
  90210. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90211. }
  90212. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90213. // Store original position and reset mesh to origin before computing the bounding box
  90214. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90215. this._tmpVector.copyFrom(this.attachedMesh.position);
  90216. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90217. this.attachedMesh.position.set(0, 0, 0);
  90218. // Update bounding dimensions/positions
  90219. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90220. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90221. // Update gizmo to match bounding box scaling and rotation
  90222. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90223. 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);
  90224. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90225. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90226. this._lineBoundingBox.computeWorldMatrix();
  90227. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90228. // restore position/rotation values
  90229. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90230. this.attachedMesh.position.copyFrom(this._tmpVector);
  90231. this._recurseComputeWorld(this.attachedMesh);
  90232. }
  90233. // Update rotation sphere locations
  90234. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90235. for (var i = 0; i < 3; i++) {
  90236. for (var j = 0; j < 2; j++) {
  90237. for (var k = 0; k < 2; k++) {
  90238. var index = ((i * 4) + (j * 2)) + k;
  90239. if (i == 0) {
  90240. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90241. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90242. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90243. }
  90244. if (i == 1) {
  90245. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90246. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90247. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90248. }
  90249. if (i == 2) {
  90250. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90251. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90252. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90253. }
  90254. if (this.fixedDragMeshScreenSize) {
  90255. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90256. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90257. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90258. }
  90259. else {
  90260. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90261. }
  90262. }
  90263. }
  90264. }
  90265. // Update scale box locations
  90266. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90267. for (var i = 0; i < 2; i++) {
  90268. for (var j = 0; j < 2; j++) {
  90269. for (var k = 0; k < 2; k++) {
  90270. var index = ((i * 4) + (j * 2)) + k;
  90271. if (scaleBoxes[index]) {
  90272. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90273. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90274. if (this.fixedDragMeshScreenSize) {
  90275. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90276. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90277. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90278. }
  90279. else {
  90280. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90281. }
  90282. }
  90283. }
  90284. }
  90285. }
  90286. };
  90287. /**
  90288. * Enables rotation on the specified axis and disables rotation on the others
  90289. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90290. */
  90291. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90292. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90293. if (i < 4) {
  90294. m.setEnabled(axis.indexOf("x") != -1);
  90295. }
  90296. else if (i < 8) {
  90297. m.setEnabled(axis.indexOf("y") != -1);
  90298. }
  90299. else {
  90300. m.setEnabled(axis.indexOf("z") != -1);
  90301. }
  90302. });
  90303. };
  90304. /**
  90305. * Disposes of the gizmo
  90306. */
  90307. BoundingBoxGizmo.prototype.dispose = function () {
  90308. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90309. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90310. this._lineBoundingBox.dispose();
  90311. this._rotateSpheresParent.dispose();
  90312. this._scaleBoxesParent.dispose();
  90313. _super.prototype.dispose.call(this);
  90314. };
  90315. /**
  90316. * 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)
  90317. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  90318. * @returns the bounding box mesh with the passed in mesh as a child
  90319. */
  90320. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  90321. var makeNotPickable = function (root) {
  90322. root.isPickable = false;
  90323. root.getChildMeshes().forEach(function (c) {
  90324. makeNotPickable(c);
  90325. });
  90326. };
  90327. makeNotPickable(mesh);
  90328. // Reset position to get boudning box from origin with no rotation
  90329. if (!mesh.rotationQuaternion) {
  90330. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  90331. }
  90332. var oldPos = mesh.position.clone();
  90333. var oldRot = mesh.rotationQuaternion.clone();
  90334. mesh.rotationQuaternion.set(0, 0, 0, 1);
  90335. mesh.position.set(0, 0, 0);
  90336. // Update bounding dimensions/positions
  90337. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  90338. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  90339. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  90340. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  90341. // Restore original positions
  90342. mesh.addChild(box);
  90343. mesh.rotationQuaternion.copyFrom(oldRot);
  90344. mesh.position.copyFrom(oldPos);
  90345. // Reverse parenting
  90346. mesh.removeChild(box);
  90347. box.addChild(mesh);
  90348. box.visibility = 0;
  90349. return box;
  90350. };
  90351. return BoundingBoxGizmo;
  90352. }(BABYLON.Gizmo));
  90353. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90354. })(BABYLON || (BABYLON = {}));
  90355. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90356. var BABYLON;
  90357. (function (BABYLON) {
  90358. /**
  90359. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90360. */
  90361. var GizmoManager = /** @class */ (function () {
  90362. /**
  90363. * Instatiates a gizmo manager
  90364. * @param scene the scene to overlay the gizmos on top of
  90365. */
  90366. function GizmoManager(scene) {
  90367. var _this = this;
  90368. this.scene = scene;
  90369. this._pointerObserver = null;
  90370. this._attachedMesh = null;
  90371. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  90372. this._boundingBoxUtilLayer = null;
  90373. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  90374. /**
  90375. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  90376. */
  90377. this.attachableMeshes = null;
  90378. /**
  90379. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  90380. */
  90381. this.usePointerToAttachGizmos = true;
  90382. this._gizmoSet = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  90383. // Instatiate/dispose gizmos based on pointer actions
  90384. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90385. if (!_this.usePointerToAttachGizmos) {
  90386. return;
  90387. }
  90388. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90389. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90390. var node = pointerInfo.pickInfo.pickedMesh;
  90391. if (_this.attachableMeshes == null) {
  90392. // Attach to the most parent node
  90393. while (node && node.parent != null) {
  90394. node = node.parent;
  90395. }
  90396. }
  90397. else {
  90398. // Attach to the parent node that is an attachableMesh
  90399. var found = false;
  90400. _this.attachableMeshes.forEach(function (mesh) {
  90401. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  90402. node = mesh;
  90403. found = true;
  90404. }
  90405. });
  90406. if (!found) {
  90407. node = null;
  90408. }
  90409. }
  90410. if (node instanceof BABYLON.AbstractMesh) {
  90411. _this.attachToMesh(node);
  90412. }
  90413. }
  90414. else {
  90415. _this.attachToMesh(null);
  90416. }
  90417. }
  90418. });
  90419. }
  90420. /**
  90421. * Attaches a set of gizmos to the specified mesh
  90422. * @param mesh The mesh the gizmo's should be attached to
  90423. */
  90424. GizmoManager.prototype.attachToMesh = function (mesh) {
  90425. if (this._attachedMesh) {
  90426. this._attachedMesh.removeBehavior(this._dragBehavior);
  90427. }
  90428. this._attachedMesh = mesh;
  90429. for (var key in this._gizmoSet) {
  90430. var gizmo = (this._gizmoSet[key]);
  90431. if (gizmo) {
  90432. gizmo.attachedMesh = mesh;
  90433. }
  90434. }
  90435. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  90436. this._attachedMesh.addBehavior(this._dragBehavior);
  90437. }
  90438. };
  90439. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  90440. get: function () {
  90441. return this._gizmoSet.positionGizmo != null;
  90442. },
  90443. /**
  90444. * If the position gizmo is enabled
  90445. */
  90446. set: function (value) {
  90447. if (value) {
  90448. this._gizmoSet.positionGizmo = this._gizmoSet.positionGizmo || new BABYLON.PositionGizmo();
  90449. this._gizmoSet.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90450. this._gizmoSet.positionGizmo.attachedMesh = this._attachedMesh;
  90451. }
  90452. else if (this._gizmoSet.positionGizmo) {
  90453. this._gizmoSet.positionGizmo.dispose();
  90454. this._gizmoSet.positionGizmo = null;
  90455. }
  90456. },
  90457. enumerable: true,
  90458. configurable: true
  90459. });
  90460. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  90461. get: function () {
  90462. return this._gizmoSet.rotationGizmo != null;
  90463. },
  90464. /**
  90465. * If the rotation gizmo is enabled
  90466. */
  90467. set: function (value) {
  90468. if (value) {
  90469. this._gizmoSet.rotationGizmo = this._gizmoSet.rotationGizmo || new BABYLON.RotationGizmo();
  90470. this._gizmoSet.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  90471. this._gizmoSet.rotationGizmo.attachedMesh = this._attachedMesh;
  90472. }
  90473. else if (this._gizmoSet.rotationGizmo) {
  90474. this._gizmoSet.rotationGizmo.dispose();
  90475. this._gizmoSet.rotationGizmo = null;
  90476. }
  90477. },
  90478. enumerable: true,
  90479. configurable: true
  90480. });
  90481. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  90482. get: function () {
  90483. return this._gizmoSet.scaleGizmo != null;
  90484. },
  90485. /**
  90486. * If the scale gizmo is enabled
  90487. */
  90488. set: function (value) {
  90489. if (value) {
  90490. this._gizmoSet.scaleGizmo = this._gizmoSet.scaleGizmo || new BABYLON.ScaleGizmo();
  90491. this._gizmoSet.scaleGizmo.attachedMesh = this._attachedMesh;
  90492. }
  90493. else if (this._gizmoSet.scaleGizmo) {
  90494. this._gizmoSet.scaleGizmo.dispose();
  90495. this._gizmoSet.scaleGizmo = null;
  90496. }
  90497. },
  90498. enumerable: true,
  90499. configurable: true
  90500. });
  90501. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  90502. get: function () {
  90503. return this._gizmoSet.boundingBoxGizmo != null;
  90504. },
  90505. /**
  90506. * If the boundingBox gizmo is enabled
  90507. */
  90508. set: function (value) {
  90509. if (value) {
  90510. if (!this._boundingBoxUtilLayer) {
  90511. this._boundingBoxUtilLayer = new BABYLON.UtilityLayerRenderer(this.scene);
  90512. this._boundingBoxUtilLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90513. }
  90514. this._gizmoSet.boundingBoxGizmo = this._gizmoSet.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._boundingBoxUtilLayer);
  90515. this._gizmoSet.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  90516. if (this._attachedMesh) {
  90517. this._attachedMesh.removeBehavior(this._dragBehavior);
  90518. this._attachedMesh.addBehavior(this._dragBehavior);
  90519. }
  90520. }
  90521. else if (this._gizmoSet.boundingBoxGizmo) {
  90522. this._gizmoSet.boundingBoxGizmo.dispose();
  90523. this._gizmoSet.boundingBoxGizmo = null;
  90524. }
  90525. },
  90526. enumerable: true,
  90527. configurable: true
  90528. });
  90529. /**
  90530. * Disposes of the gizmo manager
  90531. */
  90532. GizmoManager.prototype.dispose = function () {
  90533. this.scene.onPointerObservable.remove(this._pointerObserver);
  90534. for (var key in this._gizmoSet) {
  90535. var gizmo = (this._gizmoSet[key]);
  90536. if (gizmo) {
  90537. gizmo.dispose();
  90538. }
  90539. }
  90540. this._gizmoLayer.dispose();
  90541. };
  90542. return GizmoManager;
  90543. }());
  90544. BABYLON.GizmoManager = GizmoManager;
  90545. })(BABYLON || (BABYLON = {}));
  90546. //# sourceMappingURL=babylon.gizmoManager.js.map
  90547. var BABYLON;
  90548. (function (BABYLON) {
  90549. /**
  90550. * Defines a target to use with MorphTargetManager
  90551. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90552. */
  90553. var MorphTarget = /** @class */ (function () {
  90554. /**
  90555. * Creates a new MorphTarget
  90556. * @param name defines the name of the target
  90557. * @param influence defines the influence to use
  90558. */
  90559. function MorphTarget(
  90560. /** defines the name of the target */
  90561. name, influence, scene) {
  90562. if (influence === void 0) { influence = 0; }
  90563. if (scene === void 0) { scene = null; }
  90564. this.name = name;
  90565. /**
  90566. * Gets or sets the list of animations
  90567. */
  90568. this.animations = new Array();
  90569. this._positions = null;
  90570. this._normals = null;
  90571. this._tangents = null;
  90572. /**
  90573. * Observable raised when the influence changes
  90574. */
  90575. this.onInfluenceChanged = new BABYLON.Observable();
  90576. this._animationPropertiesOverride = null;
  90577. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90578. this.influence = influence;
  90579. }
  90580. Object.defineProperty(MorphTarget.prototype, "influence", {
  90581. /**
  90582. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90583. */
  90584. get: function () {
  90585. return this._influence;
  90586. },
  90587. set: function (influence) {
  90588. if (this._influence === influence) {
  90589. return;
  90590. }
  90591. var previous = this._influence;
  90592. this._influence = influence;
  90593. if (this.onInfluenceChanged.hasObservers) {
  90594. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90595. }
  90596. },
  90597. enumerable: true,
  90598. configurable: true
  90599. });
  90600. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90601. /**
  90602. * Gets or sets the animation properties override
  90603. */
  90604. get: function () {
  90605. if (!this._animationPropertiesOverride && this._scene) {
  90606. return this._scene.animationPropertiesOverride;
  90607. }
  90608. return this._animationPropertiesOverride;
  90609. },
  90610. set: function (value) {
  90611. this._animationPropertiesOverride = value;
  90612. },
  90613. enumerable: true,
  90614. configurable: true
  90615. });
  90616. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90617. /**
  90618. * Gets a boolean defining if the target contains position data
  90619. */
  90620. get: function () {
  90621. return !!this._positions;
  90622. },
  90623. enumerable: true,
  90624. configurable: true
  90625. });
  90626. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90627. /**
  90628. * Gets a boolean defining if the target contains normal data
  90629. */
  90630. get: function () {
  90631. return !!this._normals;
  90632. },
  90633. enumerable: true,
  90634. configurable: true
  90635. });
  90636. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90637. /**
  90638. * Gets a boolean defining if the target contains tangent data
  90639. */
  90640. get: function () {
  90641. return !!this._tangents;
  90642. },
  90643. enumerable: true,
  90644. configurable: true
  90645. });
  90646. /**
  90647. * Affects position data to this target
  90648. * @param data defines the position data to use
  90649. */
  90650. MorphTarget.prototype.setPositions = function (data) {
  90651. this._positions = data;
  90652. };
  90653. /**
  90654. * Gets the position data stored in this target
  90655. * @returns a FloatArray containing the position data (or null if not present)
  90656. */
  90657. MorphTarget.prototype.getPositions = function () {
  90658. return this._positions;
  90659. };
  90660. /**
  90661. * Affects normal data to this target
  90662. * @param data defines the normal data to use
  90663. */
  90664. MorphTarget.prototype.setNormals = function (data) {
  90665. this._normals = data;
  90666. };
  90667. /**
  90668. * Gets the normal data stored in this target
  90669. * @returns a FloatArray containing the normal data (or null if not present)
  90670. */
  90671. MorphTarget.prototype.getNormals = function () {
  90672. return this._normals;
  90673. };
  90674. /**
  90675. * Affects tangent data to this target
  90676. * @param data defines the tangent data to use
  90677. */
  90678. MorphTarget.prototype.setTangents = function (data) {
  90679. this._tangents = data;
  90680. };
  90681. /**
  90682. * Gets the tangent data stored in this target
  90683. * @returns a FloatArray containing the tangent data (or null if not present)
  90684. */
  90685. MorphTarget.prototype.getTangents = function () {
  90686. return this._tangents;
  90687. };
  90688. /**
  90689. * Serializes the current target into a Serialization object
  90690. * @returns the serialized object
  90691. */
  90692. MorphTarget.prototype.serialize = function () {
  90693. var serializationObject = {};
  90694. serializationObject.name = this.name;
  90695. serializationObject.influence = this.influence;
  90696. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90697. if (this.hasNormals) {
  90698. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90699. }
  90700. if (this.hasTangents) {
  90701. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90702. }
  90703. // Animations
  90704. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90705. return serializationObject;
  90706. };
  90707. // Statics
  90708. /**
  90709. * Creates a new target from serialized data
  90710. * @param serializationObject defines the serialized data to use
  90711. * @returns a new MorphTarget
  90712. */
  90713. MorphTarget.Parse = function (serializationObject) {
  90714. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90715. result.setPositions(serializationObject.positions);
  90716. if (serializationObject.normals) {
  90717. result.setNormals(serializationObject.normals);
  90718. }
  90719. if (serializationObject.tangents) {
  90720. result.setTangents(serializationObject.tangents);
  90721. }
  90722. // Animations
  90723. if (serializationObject.animations) {
  90724. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90725. var parsedAnimation = serializationObject.animations[animationIndex];
  90726. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90727. }
  90728. }
  90729. return result;
  90730. };
  90731. /**
  90732. * Creates a MorphTarget from mesh data
  90733. * @param mesh defines the source mesh
  90734. * @param name defines the name to use for the new target
  90735. * @param influence defines the influence to attach to the target
  90736. * @returns a new MorphTarget
  90737. */
  90738. MorphTarget.FromMesh = function (mesh, name, influence) {
  90739. if (!name) {
  90740. name = mesh.name;
  90741. }
  90742. var result = new MorphTarget(name, influence, mesh.getScene());
  90743. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90744. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90745. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90746. }
  90747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90748. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90749. }
  90750. return result;
  90751. };
  90752. return MorphTarget;
  90753. }());
  90754. BABYLON.MorphTarget = MorphTarget;
  90755. })(BABYLON || (BABYLON = {}));
  90756. //# sourceMappingURL=babylon.morphTarget.js.map
  90757. var BABYLON;
  90758. (function (BABYLON) {
  90759. /**
  90760. * This class is used to deform meshes using morphing between different targets
  90761. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90762. */
  90763. var MorphTargetManager = /** @class */ (function () {
  90764. /**
  90765. * Creates a new MorphTargetManager
  90766. * @param scene defines the current scene
  90767. */
  90768. function MorphTargetManager(scene) {
  90769. if (scene === void 0) { scene = null; }
  90770. this._targets = new Array();
  90771. this._targetObservable = new Array();
  90772. this._activeTargets = new BABYLON.SmartArray(16);
  90773. this._supportsNormals = false;
  90774. this._supportsTangents = false;
  90775. this._vertexCount = 0;
  90776. this._uniqueId = 0;
  90777. this._tempInfluences = new Array();
  90778. if (!scene) {
  90779. scene = BABYLON.Engine.LastCreatedScene;
  90780. }
  90781. this._scene = scene;
  90782. if (this._scene) {
  90783. this._scene.morphTargetManagers.push(this);
  90784. this._uniqueId = this._scene.getUniqueId();
  90785. }
  90786. }
  90787. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90788. /**
  90789. * Gets the unique ID of this manager
  90790. */
  90791. get: function () {
  90792. return this._uniqueId;
  90793. },
  90794. enumerable: true,
  90795. configurable: true
  90796. });
  90797. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90798. /**
  90799. * Gets the number of vertices handled by this manager
  90800. */
  90801. get: function () {
  90802. return this._vertexCount;
  90803. },
  90804. enumerable: true,
  90805. configurable: true
  90806. });
  90807. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90808. /**
  90809. * Gets a boolean indicating if this manager supports morphing of normals
  90810. */
  90811. get: function () {
  90812. return this._supportsNormals;
  90813. },
  90814. enumerable: true,
  90815. configurable: true
  90816. });
  90817. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90818. /**
  90819. * Gets a boolean indicating if this manager supports morphing of tangents
  90820. */
  90821. get: function () {
  90822. return this._supportsTangents;
  90823. },
  90824. enumerable: true,
  90825. configurable: true
  90826. });
  90827. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90828. /**
  90829. * Gets the number of targets stored in this manager
  90830. */
  90831. get: function () {
  90832. return this._targets.length;
  90833. },
  90834. enumerable: true,
  90835. configurable: true
  90836. });
  90837. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90838. /**
  90839. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90840. */
  90841. get: function () {
  90842. return this._activeTargets.length;
  90843. },
  90844. enumerable: true,
  90845. configurable: true
  90846. });
  90847. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90848. /**
  90849. * Gets the list of influences (one per target)
  90850. */
  90851. get: function () {
  90852. return this._influences;
  90853. },
  90854. enumerable: true,
  90855. configurable: true
  90856. });
  90857. /**
  90858. * Gets the active target at specified index. An active target is a target with an influence > 0
  90859. * @param index defines the index to check
  90860. * @returns the requested target
  90861. */
  90862. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90863. return this._activeTargets.data[index];
  90864. };
  90865. /**
  90866. * Gets the target at specified index
  90867. * @param index defines the index to check
  90868. * @returns the requested target
  90869. */
  90870. MorphTargetManager.prototype.getTarget = function (index) {
  90871. return this._targets[index];
  90872. };
  90873. /**
  90874. * Add a new target to this manager
  90875. * @param target defines the target to add
  90876. */
  90877. MorphTargetManager.prototype.addTarget = function (target) {
  90878. var _this = this;
  90879. this._targets.push(target);
  90880. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90881. _this._syncActiveTargets(needUpdate);
  90882. }));
  90883. this._syncActiveTargets(true);
  90884. };
  90885. /**
  90886. * Removes a target from the manager
  90887. * @param target defines the target to remove
  90888. */
  90889. MorphTargetManager.prototype.removeTarget = function (target) {
  90890. var index = this._targets.indexOf(target);
  90891. if (index >= 0) {
  90892. this._targets.splice(index, 1);
  90893. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90894. this._syncActiveTargets(true);
  90895. }
  90896. };
  90897. /**
  90898. * Serializes the current manager into a Serialization object
  90899. * @returns the serialized object
  90900. */
  90901. MorphTargetManager.prototype.serialize = function () {
  90902. var serializationObject = {};
  90903. serializationObject.id = this.uniqueId;
  90904. serializationObject.targets = [];
  90905. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90906. var target = _a[_i];
  90907. serializationObject.targets.push(target.serialize());
  90908. }
  90909. return serializationObject;
  90910. };
  90911. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90912. var influenceCount = 0;
  90913. this._activeTargets.reset();
  90914. this._supportsNormals = true;
  90915. this._supportsTangents = true;
  90916. this._vertexCount = 0;
  90917. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90918. var target = _a[_i];
  90919. this._activeTargets.push(target);
  90920. this._tempInfluences[influenceCount++] = target.influence;
  90921. var positions = target.getPositions();
  90922. if (positions) {
  90923. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90924. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90925. var vertexCount = positions.length / 3;
  90926. if (this._vertexCount === 0) {
  90927. this._vertexCount = vertexCount;
  90928. }
  90929. else if (this._vertexCount !== vertexCount) {
  90930. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90931. return;
  90932. }
  90933. }
  90934. }
  90935. if (!this._influences || this._influences.length !== influenceCount) {
  90936. this._influences = new Float32Array(influenceCount);
  90937. }
  90938. for (var index = 0; index < influenceCount; index++) {
  90939. this._influences[index] = this._tempInfluences[index];
  90940. }
  90941. if (needUpdate) {
  90942. this.synchronize();
  90943. }
  90944. };
  90945. /**
  90946. * Syncrhonize the targets with all the meshes using this morph target manager
  90947. */
  90948. MorphTargetManager.prototype.synchronize = function () {
  90949. if (!this._scene) {
  90950. return;
  90951. }
  90952. // Flag meshes as dirty to resync with the active targets
  90953. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90954. var mesh = _a[_i];
  90955. if (mesh.morphTargetManager === this) {
  90956. mesh._syncGeometryWithMorphTargetManager();
  90957. }
  90958. }
  90959. };
  90960. // Statics
  90961. /**
  90962. * Creates a new MorphTargetManager from serialized data
  90963. * @param serializationObject defines the serialized data
  90964. * @param scene defines the hosting scene
  90965. * @returns the new MorphTargetManager
  90966. */
  90967. MorphTargetManager.Parse = function (serializationObject, scene) {
  90968. var result = new MorphTargetManager(scene);
  90969. result._uniqueId = serializationObject.id;
  90970. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90971. var targetData = _a[_i];
  90972. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90973. }
  90974. return result;
  90975. };
  90976. return MorphTargetManager;
  90977. }());
  90978. BABYLON.MorphTargetManager = MorphTargetManager;
  90979. })(BABYLON || (BABYLON = {}));
  90980. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90981. var BABYLON;
  90982. (function (BABYLON) {
  90983. var Octree = /** @class */ (function () {
  90984. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90985. if (maxDepth === void 0) { maxDepth = 2; }
  90986. this.maxDepth = maxDepth;
  90987. this.dynamicContent = new Array();
  90988. this._maxBlockCapacity = maxBlockCapacity || 64;
  90989. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90990. this._creationFunc = creationFunc;
  90991. }
  90992. // Methods
  90993. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90994. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90995. };
  90996. Octree.prototype.addMesh = function (entry) {
  90997. for (var index = 0; index < this.blocks.length; index++) {
  90998. var block = this.blocks[index];
  90999. block.addEntry(entry);
  91000. }
  91001. };
  91002. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91003. this._selectionContent.reset();
  91004. for (var index = 0; index < this.blocks.length; index++) {
  91005. var block = this.blocks[index];
  91006. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91007. }
  91008. if (allowDuplicate) {
  91009. this._selectionContent.concat(this.dynamicContent);
  91010. }
  91011. else {
  91012. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91013. }
  91014. return this._selectionContent;
  91015. };
  91016. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91017. this._selectionContent.reset();
  91018. for (var index = 0; index < this.blocks.length; index++) {
  91019. var block = this.blocks[index];
  91020. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91021. }
  91022. if (allowDuplicate) {
  91023. this._selectionContent.concat(this.dynamicContent);
  91024. }
  91025. else {
  91026. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91027. }
  91028. return this._selectionContent;
  91029. };
  91030. Octree.prototype.intersectsRay = function (ray) {
  91031. this._selectionContent.reset();
  91032. for (var index = 0; index < this.blocks.length; index++) {
  91033. var block = this.blocks[index];
  91034. block.intersectsRay(ray, this._selectionContent);
  91035. }
  91036. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91037. return this._selectionContent;
  91038. };
  91039. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91040. target.blocks = new Array();
  91041. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91042. // Segmenting space
  91043. for (var x = 0; x < 2; x++) {
  91044. for (var y = 0; y < 2; y++) {
  91045. for (var z = 0; z < 2; z++) {
  91046. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91047. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91048. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91049. block.addEntries(entries);
  91050. target.blocks.push(block);
  91051. }
  91052. }
  91053. }
  91054. };
  91055. Octree.CreationFuncForMeshes = function (entry, block) {
  91056. var boundingInfo = entry.getBoundingInfo();
  91057. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91058. block.entries.push(entry);
  91059. }
  91060. };
  91061. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91062. var boundingInfo = entry.getBoundingInfo();
  91063. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91064. block.entries.push(entry);
  91065. }
  91066. };
  91067. return Octree;
  91068. }());
  91069. BABYLON.Octree = Octree;
  91070. })(BABYLON || (BABYLON = {}));
  91071. //# sourceMappingURL=babylon.octree.js.map
  91072. var BABYLON;
  91073. (function (BABYLON) {
  91074. var OctreeBlock = /** @class */ (function () {
  91075. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91076. this.entries = new Array();
  91077. this._boundingVectors = new Array();
  91078. this._capacity = capacity;
  91079. this._depth = depth;
  91080. this._maxDepth = maxDepth;
  91081. this._creationFunc = creationFunc;
  91082. this._minPoint = minPoint;
  91083. this._maxPoint = maxPoint;
  91084. this._boundingVectors.push(minPoint.clone());
  91085. this._boundingVectors.push(maxPoint.clone());
  91086. this._boundingVectors.push(minPoint.clone());
  91087. this._boundingVectors[2].x = maxPoint.x;
  91088. this._boundingVectors.push(minPoint.clone());
  91089. this._boundingVectors[3].y = maxPoint.y;
  91090. this._boundingVectors.push(minPoint.clone());
  91091. this._boundingVectors[4].z = maxPoint.z;
  91092. this._boundingVectors.push(maxPoint.clone());
  91093. this._boundingVectors[5].z = minPoint.z;
  91094. this._boundingVectors.push(maxPoint.clone());
  91095. this._boundingVectors[6].x = minPoint.x;
  91096. this._boundingVectors.push(maxPoint.clone());
  91097. this._boundingVectors[7].y = minPoint.y;
  91098. }
  91099. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91100. // Property
  91101. get: function () {
  91102. return this._capacity;
  91103. },
  91104. enumerable: true,
  91105. configurable: true
  91106. });
  91107. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91108. get: function () {
  91109. return this._minPoint;
  91110. },
  91111. enumerable: true,
  91112. configurable: true
  91113. });
  91114. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91115. get: function () {
  91116. return this._maxPoint;
  91117. },
  91118. enumerable: true,
  91119. configurable: true
  91120. });
  91121. // Methods
  91122. OctreeBlock.prototype.addEntry = function (entry) {
  91123. if (this.blocks) {
  91124. for (var index = 0; index < this.blocks.length; index++) {
  91125. var block = this.blocks[index];
  91126. block.addEntry(entry);
  91127. }
  91128. return;
  91129. }
  91130. this._creationFunc(entry, this);
  91131. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91132. this.createInnerBlocks();
  91133. }
  91134. };
  91135. OctreeBlock.prototype.addEntries = function (entries) {
  91136. for (var index = 0; index < entries.length; index++) {
  91137. var mesh = entries[index];
  91138. this.addEntry(mesh);
  91139. }
  91140. };
  91141. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91142. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91143. if (this.blocks) {
  91144. for (var index = 0; index < this.blocks.length; index++) {
  91145. var block = this.blocks[index];
  91146. block.select(frustumPlanes, selection, allowDuplicate);
  91147. }
  91148. return;
  91149. }
  91150. if (allowDuplicate) {
  91151. selection.concat(this.entries);
  91152. }
  91153. else {
  91154. selection.concatWithNoDuplicate(this.entries);
  91155. }
  91156. }
  91157. };
  91158. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91159. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91160. if (this.blocks) {
  91161. for (var index = 0; index < this.blocks.length; index++) {
  91162. var block = this.blocks[index];
  91163. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91164. }
  91165. return;
  91166. }
  91167. if (allowDuplicate) {
  91168. selection.concat(this.entries);
  91169. }
  91170. else {
  91171. selection.concatWithNoDuplicate(this.entries);
  91172. }
  91173. }
  91174. };
  91175. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91176. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91177. if (this.blocks) {
  91178. for (var index = 0; index < this.blocks.length; index++) {
  91179. var block = this.blocks[index];
  91180. block.intersectsRay(ray, selection);
  91181. }
  91182. return;
  91183. }
  91184. selection.concatWithNoDuplicate(this.entries);
  91185. }
  91186. };
  91187. OctreeBlock.prototype.createInnerBlocks = function () {
  91188. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91189. };
  91190. return OctreeBlock;
  91191. }());
  91192. BABYLON.OctreeBlock = OctreeBlock;
  91193. })(BABYLON || (BABYLON = {}));
  91194. //# sourceMappingURL=babylon.octreeBlock.js.map
  91195. var BABYLON;
  91196. (function (BABYLON) {
  91197. /**
  91198. * Postprocess used to generate anaglyphic rendering
  91199. */
  91200. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91201. __extends(AnaglyphPostProcess, _super);
  91202. /**
  91203. * Creates a new AnaglyphPostProcess
  91204. * @param name defines postprocess name
  91205. * @param options defines creation options or target ratio scale
  91206. * @param rigCameras defines cameras using this postprocess
  91207. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91208. * @param engine defines hosting engine
  91209. * @param reusable defines if the postprocess will be reused multiple times per frame
  91210. */
  91211. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91212. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91213. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91214. _this.onApplyObservable.add(function (effect) {
  91215. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91216. });
  91217. return _this;
  91218. }
  91219. return AnaglyphPostProcess;
  91220. }(BABYLON.PostProcess));
  91221. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91222. })(BABYLON || (BABYLON = {}));
  91223. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91224. var BABYLON;
  91225. (function (BABYLON) {
  91226. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91227. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91228. });
  91229. /**
  91230. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91231. */
  91232. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91233. __extends(AnaglyphArcRotateCamera, _super);
  91234. /**
  91235. * Creates a new AnaglyphArcRotateCamera
  91236. * @param name defines camera name
  91237. * @param alpha defines alpha angle (in radians)
  91238. * @param beta defines beta angle (in radians)
  91239. * @param radius defines radius
  91240. * @param target defines camera target
  91241. * @param interaxialDistance defines distance between each color axis
  91242. * @param scene defines the hosting scene
  91243. */
  91244. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91245. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91246. _this.interaxialDistance = interaxialDistance;
  91247. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91248. return _this;
  91249. }
  91250. /**
  91251. * Gets camera class name
  91252. * @returns AnaglyphArcRotateCamera
  91253. */
  91254. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91255. return "AnaglyphArcRotateCamera";
  91256. };
  91257. return AnaglyphArcRotateCamera;
  91258. }(BABYLON.ArcRotateCamera));
  91259. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91260. })(BABYLON || (BABYLON = {}));
  91261. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  91262. var BABYLON;
  91263. (function (BABYLON) {
  91264. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  91265. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91266. });
  91267. /**
  91268. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91269. */
  91270. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91271. __extends(AnaglyphFreeCamera, _super);
  91272. /**
  91273. * Creates a new AnaglyphFreeCamera
  91274. * @param name defines camera name
  91275. * @param position defines initial position
  91276. * @param interaxialDistance defines distance between each color axis
  91277. * @param scene defines the hosting scene
  91278. */
  91279. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91280. var _this = _super.call(this, name, position, scene) || this;
  91281. _this.interaxialDistance = interaxialDistance;
  91282. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91283. return _this;
  91284. }
  91285. /**
  91286. * Gets camera class name
  91287. * @returns AnaglyphFreeCamera
  91288. */
  91289. AnaglyphFreeCamera.prototype.getClassName = function () {
  91290. return "AnaglyphFreeCamera";
  91291. };
  91292. return AnaglyphFreeCamera;
  91293. }(BABYLON.FreeCamera));
  91294. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91295. })(BABYLON || (BABYLON = {}));
  91296. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  91297. var BABYLON;
  91298. (function (BABYLON) {
  91299. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  91300. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91301. });
  91302. /**
  91303. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91304. */
  91305. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91306. __extends(AnaglyphGamepadCamera, _super);
  91307. /**
  91308. * Creates a new AnaglyphGamepadCamera
  91309. * @param name defines camera name
  91310. * @param position defines initial position
  91311. * @param interaxialDistance defines distance between each color axis
  91312. * @param scene defines the hosting scene
  91313. */
  91314. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91315. var _this = _super.call(this, name, position, scene) || this;
  91316. _this.interaxialDistance = interaxialDistance;
  91317. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91318. return _this;
  91319. }
  91320. /**
  91321. * Gets camera class name
  91322. * @returns AnaglyphGamepadCamera
  91323. */
  91324. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91325. return "AnaglyphGamepadCamera";
  91326. };
  91327. return AnaglyphGamepadCamera;
  91328. }(BABYLON.GamepadCamera));
  91329. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91330. })(BABYLON || (BABYLON = {}));
  91331. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  91332. var BABYLON;
  91333. (function (BABYLON) {
  91334. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  91335. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91336. });
  91337. /**
  91338. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91339. */
  91340. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91341. __extends(AnaglyphUniversalCamera, _super);
  91342. /**
  91343. * Creates a new AnaglyphUniversalCamera
  91344. * @param name defines camera name
  91345. * @param position defines initial position
  91346. * @param interaxialDistance defines distance between each color axis
  91347. * @param scene defines the hosting scene
  91348. */
  91349. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91350. var _this = _super.call(this, name, position, scene) || this;
  91351. _this.interaxialDistance = interaxialDistance;
  91352. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91353. return _this;
  91354. }
  91355. /**
  91356. * Gets camera class name
  91357. * @returns AnaglyphUniversalCamera
  91358. */
  91359. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91360. return "AnaglyphUniversalCamera";
  91361. };
  91362. return AnaglyphUniversalCamera;
  91363. }(BABYLON.UniversalCamera));
  91364. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91365. })(BABYLON || (BABYLON = {}));
  91366. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  91367. var BABYLON;
  91368. (function (BABYLON) {
  91369. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91370. __extends(StereoscopicInterlacePostProcess, _super);
  91371. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91372. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91373. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91374. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91375. _this.onSizeChangedObservable.add(function () {
  91376. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91377. });
  91378. _this.onApplyObservable.add(function (effect) {
  91379. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91380. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91381. });
  91382. return _this;
  91383. }
  91384. return StereoscopicInterlacePostProcess;
  91385. }(BABYLON.PostProcess));
  91386. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91387. })(BABYLON || (BABYLON = {}));
  91388. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91389. var BABYLON;
  91390. (function (BABYLON) {
  91391. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  91392. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91393. });
  91394. /**
  91395. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91396. */
  91397. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91398. __extends(StereoscopicArcRotateCamera, _super);
  91399. /**
  91400. * Creates a new StereoscopicArcRotateCamera
  91401. * @param name defines camera name
  91402. * @param alpha defines alpha angle (in radians)
  91403. * @param beta defines beta angle (in radians)
  91404. * @param radius defines radius
  91405. * @param target defines camera target
  91406. * @param interaxialDistance defines distance between each color axis
  91407. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91408. * @param scene defines the hosting scene
  91409. */
  91410. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91411. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91412. _this.interaxialDistance = interaxialDistance;
  91413. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91414. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91415. return _this;
  91416. }
  91417. /**
  91418. * Gets camera class name
  91419. * @returns StereoscopicArcRotateCamera
  91420. */
  91421. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91422. return "StereoscopicArcRotateCamera";
  91423. };
  91424. return StereoscopicArcRotateCamera;
  91425. }(BABYLON.ArcRotateCamera));
  91426. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91427. })(BABYLON || (BABYLON = {}));
  91428. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  91429. var BABYLON;
  91430. (function (BABYLON) {
  91431. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91432. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91433. });
  91434. /**
  91435. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91436. */
  91437. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91438. __extends(StereoscopicFreeCamera, _super);
  91439. /**
  91440. * Creates a new StereoscopicFreeCamera
  91441. * @param name defines camera name
  91442. * @param position defines initial position
  91443. * @param interaxialDistance defines distance between each color axis
  91444. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91445. * @param scene defines the hosting scene
  91446. */
  91447. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91448. var _this = _super.call(this, name, position, scene) || this;
  91449. _this.interaxialDistance = interaxialDistance;
  91450. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91451. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91452. return _this;
  91453. }
  91454. /**
  91455. * Gets camera class name
  91456. * @returns StereoscopicFreeCamera
  91457. */
  91458. StereoscopicFreeCamera.prototype.getClassName = function () {
  91459. return "StereoscopicFreeCamera";
  91460. };
  91461. return StereoscopicFreeCamera;
  91462. }(BABYLON.FreeCamera));
  91463. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91464. })(BABYLON || (BABYLON = {}));
  91465. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  91466. var BABYLON;
  91467. (function (BABYLON) {
  91468. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  91469. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91470. });
  91471. /**
  91472. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91473. */
  91474. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91475. __extends(StereoscopicGamepadCamera, _super);
  91476. /**
  91477. * Creates a new StereoscopicGamepadCamera
  91478. * @param name defines camera name
  91479. * @param position defines initial position
  91480. * @param interaxialDistance defines distance between each color axis
  91481. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91482. * @param scene defines the hosting scene
  91483. */
  91484. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91485. var _this = _super.call(this, name, position, scene) || this;
  91486. _this.interaxialDistance = interaxialDistance;
  91487. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91488. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91489. return _this;
  91490. }
  91491. /**
  91492. * Gets camera class name
  91493. * @returns StereoscopicGamepadCamera
  91494. */
  91495. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91496. return "StereoscopicGamepadCamera";
  91497. };
  91498. return StereoscopicGamepadCamera;
  91499. }(BABYLON.GamepadCamera));
  91500. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91501. })(BABYLON || (BABYLON = {}));
  91502. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  91503. var BABYLON;
  91504. (function (BABYLON) {
  91505. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  91506. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  91507. });
  91508. /**
  91509. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91510. */
  91511. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91512. __extends(StereoscopicUniversalCamera, _super);
  91513. /**
  91514. * Creates a new StereoscopicUniversalCamera
  91515. * @param name defines camera name
  91516. * @param position defines initial position
  91517. * @param interaxialDistance defines distance between each color axis
  91518. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91519. * @param scene defines the hosting scene
  91520. */
  91521. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91522. var _this = _super.call(this, name, position, scene) || this;
  91523. _this.interaxialDistance = interaxialDistance;
  91524. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91525. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91526. return _this;
  91527. }
  91528. /**
  91529. * Gets camera class name
  91530. * @returns StereoscopicUniversalCamera
  91531. */
  91532. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91533. return "StereoscopicUniversalCamera";
  91534. };
  91535. return StereoscopicUniversalCamera;
  91536. }(BABYLON.UniversalCamera));
  91537. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91538. })(BABYLON || (BABYLON = {}));
  91539. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  91540. var BABYLON;
  91541. (function (BABYLON) {
  91542. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91543. __extends(VRDistortionCorrectionPostProcess, _super);
  91544. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91545. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91546. 'LensCenter',
  91547. 'Scale',
  91548. 'ScaleIn',
  91549. 'HmdWarpParam'
  91550. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91551. _this._isRightEye = isRightEye;
  91552. _this._distortionFactors = vrMetrics.distortionK;
  91553. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91554. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91555. _this.adaptScaleToCurrentViewport = true;
  91556. _this.onSizeChangedObservable.add(function () {
  91557. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91558. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91559. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91560. });
  91561. _this.onApplyObservable.add(function (effect) {
  91562. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91563. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91564. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91565. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91566. });
  91567. return _this;
  91568. }
  91569. return VRDistortionCorrectionPostProcess;
  91570. }(BABYLON.PostProcess));
  91571. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91572. })(BABYLON || (BABYLON = {}));
  91573. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91574. var BABYLON;
  91575. (function (BABYLON) {
  91576. /**
  91577. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91578. * Screen rotation is taken into account.
  91579. */
  91580. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91581. function FreeCameraDeviceOrientationInput() {
  91582. var _this = this;
  91583. this._screenOrientationAngle = 0;
  91584. this._screenQuaternion = new BABYLON.Quaternion();
  91585. this._alpha = 0;
  91586. this._beta = 0;
  91587. this._gamma = 0;
  91588. this._orientationChanged = function () {
  91589. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91590. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91591. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91592. };
  91593. this._deviceOrientation = function (evt) {
  91594. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91595. _this._beta = evt.beta !== null ? evt.beta : 0;
  91596. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91597. };
  91598. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91599. this._orientationChanged();
  91600. }
  91601. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91602. get: function () {
  91603. return this._camera;
  91604. },
  91605. set: function (camera) {
  91606. this._camera = camera;
  91607. if (this._camera != null && !this._camera.rotationQuaternion) {
  91608. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91609. }
  91610. },
  91611. enumerable: true,
  91612. configurable: true
  91613. });
  91614. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91615. window.addEventListener("orientationchange", this._orientationChanged);
  91616. window.addEventListener("deviceorientation", this._deviceOrientation);
  91617. //In certain cases, the attach control is called AFTER orientation was changed,
  91618. //So this is needed.
  91619. this._orientationChanged();
  91620. };
  91621. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91622. window.removeEventListener("orientationchange", this._orientationChanged);
  91623. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91624. };
  91625. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91626. //if no device orientation provided, don't update the rotation.
  91627. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91628. if (!this._alpha)
  91629. return;
  91630. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91631. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91632. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91633. //Mirror on XY Plane
  91634. this._camera.rotationQuaternion.z *= -1;
  91635. this._camera.rotationQuaternion.w *= -1;
  91636. };
  91637. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91638. return "FreeCameraDeviceOrientationInput";
  91639. };
  91640. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91641. return "deviceOrientation";
  91642. };
  91643. return FreeCameraDeviceOrientationInput;
  91644. }());
  91645. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91646. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91647. })(BABYLON || (BABYLON = {}));
  91648. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91649. var BABYLON;
  91650. (function (BABYLON) {
  91651. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91652. function ArcRotateCameraVRDeviceOrientationInput() {
  91653. this.alphaCorrection = 1;
  91654. this.betaCorrection = 1;
  91655. this.gammaCorrection = 1;
  91656. this._alpha = 0;
  91657. this._gamma = 0;
  91658. this._dirty = false;
  91659. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91660. }
  91661. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91662. this.camera.attachControl(element, noPreventDefault);
  91663. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91664. };
  91665. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91666. if (evt.alpha !== null) {
  91667. this._alpha = +evt.alpha | 0;
  91668. }
  91669. if (evt.gamma !== null) {
  91670. this._gamma = +evt.gamma | 0;
  91671. }
  91672. this._dirty = true;
  91673. };
  91674. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91675. if (this._dirty) {
  91676. this._dirty = false;
  91677. if (this._gamma < 0) {
  91678. this._gamma = 180 + this._gamma;
  91679. }
  91680. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91681. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91682. }
  91683. };
  91684. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91685. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91686. };
  91687. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91688. return "ArcRotateCameraVRDeviceOrientationInput";
  91689. };
  91690. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91691. return "VRDeviceOrientation";
  91692. };
  91693. return ArcRotateCameraVRDeviceOrientationInput;
  91694. }());
  91695. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91696. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91697. })(BABYLON || (BABYLON = {}));
  91698. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91699. var BABYLON;
  91700. (function (BABYLON) {
  91701. var VRCameraMetrics = /** @class */ (function () {
  91702. function VRCameraMetrics() {
  91703. this.compensateDistortion = true;
  91704. }
  91705. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91706. get: function () {
  91707. return this.hResolution / (2 * this.vResolution);
  91708. },
  91709. enumerable: true,
  91710. configurable: true
  91711. });
  91712. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91713. get: function () {
  91714. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91715. },
  91716. enumerable: true,
  91717. configurable: true
  91718. });
  91719. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91720. get: function () {
  91721. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91722. var h = (4 * meters) / this.hScreenSize;
  91723. return BABYLON.Matrix.Translation(h, 0, 0);
  91724. },
  91725. enumerable: true,
  91726. configurable: true
  91727. });
  91728. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91729. get: function () {
  91730. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91731. var h = (4 * meters) / this.hScreenSize;
  91732. return BABYLON.Matrix.Translation(-h, 0, 0);
  91733. },
  91734. enumerable: true,
  91735. configurable: true
  91736. });
  91737. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91738. get: function () {
  91739. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91740. },
  91741. enumerable: true,
  91742. configurable: true
  91743. });
  91744. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91745. get: function () {
  91746. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91747. },
  91748. enumerable: true,
  91749. configurable: true
  91750. });
  91751. VRCameraMetrics.GetDefault = function () {
  91752. var result = new VRCameraMetrics();
  91753. result.hResolution = 1280;
  91754. result.vResolution = 800;
  91755. result.hScreenSize = 0.149759993;
  91756. result.vScreenSize = 0.0935999975;
  91757. result.vScreenCenter = 0.0467999987;
  91758. result.eyeToScreenDistance = 0.0410000011;
  91759. result.lensSeparationDistance = 0.0635000020;
  91760. result.interpupillaryDistance = 0.0640000030;
  91761. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91762. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91763. result.postProcessScaleFactor = 1.714605507808412;
  91764. result.lensCenterOffset = 0.151976421;
  91765. return result;
  91766. };
  91767. return VRCameraMetrics;
  91768. }());
  91769. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91770. })(BABYLON || (BABYLON = {}));
  91771. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91772. var BABYLON;
  91773. (function (BABYLON) {
  91774. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  91775. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91776. });
  91777. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  91778. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  91779. });
  91780. /**
  91781. * This represents a WebVR camera.
  91782. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91783. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91784. */
  91785. var WebVRFreeCamera = /** @class */ (function (_super) {
  91786. __extends(WebVRFreeCamera, _super);
  91787. /**
  91788. * Instantiates a WebVRFreeCamera.
  91789. * @param name The name of the WebVRFreeCamera
  91790. * @param position The starting anchor position for the camera
  91791. * @param scene The scene the camera belongs to
  91792. * @param webVROptions a set of customizable options for the webVRCamera
  91793. */
  91794. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91795. if (webVROptions === void 0) { webVROptions = {}; }
  91796. var _this = _super.call(this, name, position, scene) || this;
  91797. _this.webVROptions = webVROptions;
  91798. /**
  91799. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91800. */
  91801. _this._vrDevice = null;
  91802. /**
  91803. * The rawPose of the vrDevice.
  91804. */
  91805. _this.rawPose = null;
  91806. _this._specsVersion = "1.1";
  91807. _this._attached = false;
  91808. _this._descendants = [];
  91809. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91810. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91811. /** @hidden */
  91812. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91813. _this._standingMatrix = null;
  91814. /**
  91815. * Represents device position in babylon space.
  91816. */
  91817. _this.devicePosition = BABYLON.Vector3.Zero();
  91818. /**
  91819. * Represents device rotation in babylon space.
  91820. */
  91821. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91822. /**
  91823. * The scale of the device to be used when translating from device space to babylon space.
  91824. */
  91825. _this.deviceScaleFactor = 1;
  91826. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91827. _this._worldToDevice = BABYLON.Matrix.Identity();
  91828. /**
  91829. * References to the webVR controllers for the vrDevice.
  91830. */
  91831. _this.controllers = [];
  91832. /**
  91833. * Emits an event when a controller is attached.
  91834. */
  91835. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91836. /**
  91837. * Emits an event when a controller's mesh has been loaded;
  91838. */
  91839. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91840. /**
  91841. * Emits an event when the HMD's pose has been updated.
  91842. */
  91843. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  91844. _this._poseSet = false;
  91845. /**
  91846. * If the rig cameras be used as parent instead of this camera.
  91847. */
  91848. _this.rigParenting = true;
  91849. _this._defaultHeight = undefined;
  91850. _this._workingVector = BABYLON.Vector3.Zero();
  91851. _this._oneVector = BABYLON.Vector3.One();
  91852. _this._workingMatrix = BABYLON.Matrix.Identity();
  91853. _this._cache.position = BABYLON.Vector3.Zero();
  91854. if (webVROptions.defaultHeight) {
  91855. _this._defaultHeight = webVROptions.defaultHeight;
  91856. _this.position.y = _this._defaultHeight;
  91857. }
  91858. _this.minZ = 0.1;
  91859. //legacy support - the compensation boolean was removed.
  91860. if (arguments.length === 5) {
  91861. _this.webVROptions = arguments[4];
  91862. }
  91863. // default webVR options
  91864. if (_this.webVROptions.trackPosition == undefined) {
  91865. _this.webVROptions.trackPosition = true;
  91866. }
  91867. if (_this.webVROptions.controllerMeshes == undefined) {
  91868. _this.webVROptions.controllerMeshes = true;
  91869. }
  91870. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91871. _this.webVROptions.defaultLightingOnControllers = true;
  91872. }
  91873. _this.rotationQuaternion = new BABYLON.Quaternion();
  91874. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91875. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91876. }
  91877. //enable VR
  91878. var engine = _this.getEngine();
  91879. _this._onVREnabled = function (success) { if (success) {
  91880. _this.initControllers();
  91881. } };
  91882. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91883. engine.initWebVR().add(function (event) {
  91884. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91885. return;
  91886. }
  91887. _this._vrDevice = event.vrDisplay;
  91888. //reset the rig parameters.
  91889. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91890. if (_this._attached) {
  91891. _this.getEngine().enableVR();
  91892. }
  91893. });
  91894. if (typeof (VRFrameData) !== "undefined")
  91895. _this._frameData = new VRFrameData();
  91896. /**
  91897. * The idea behind the following lines:
  91898. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91899. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91900. * the second will not show it correctly.
  91901. *
  91902. * To solve this - each object that has the camera as parent will be added to a protected array.
  91903. * When the rig camera renders, it will take this array and set all of those to be its children.
  91904. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91905. * Amazing!
  91906. */
  91907. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91908. if (camera.parent === _this && _this.rigParenting) {
  91909. _this._descendants = _this.getDescendants(true, function (n) {
  91910. // don't take the cameras or the controllers!
  91911. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91912. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91913. return !isController && !isRigCamera;
  91914. });
  91915. _this._descendants.forEach(function (node) {
  91916. node.parent = camera;
  91917. });
  91918. }
  91919. });
  91920. scene.onAfterCameraRenderObservable.add(function (camera) {
  91921. if (camera.parent === _this && _this.rigParenting) {
  91922. _this._descendants.forEach(function (node) {
  91923. node.parent = _this;
  91924. });
  91925. }
  91926. });
  91927. return _this;
  91928. }
  91929. /**
  91930. * Gets the device distance from the ground in meters.
  91931. * @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.
  91932. */
  91933. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91934. if (this._standingMatrix) {
  91935. // Add standing matrix offset to get real offset from ground in room
  91936. this._standingMatrix.getTranslationToRef(this._workingVector);
  91937. return this._deviceRoomPosition.y + this._workingVector.y;
  91938. }
  91939. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91940. return this._defaultHeight || 0;
  91941. };
  91942. /**
  91943. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91944. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91945. */
  91946. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91947. var _this = this;
  91948. if (callback === void 0) { callback = function (bool) { }; }
  91949. // Use standing matrix if available
  91950. this.getEngine().initWebVRAsync().then(function (result) {
  91951. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91952. callback(false);
  91953. }
  91954. else {
  91955. _this._standingMatrix = new BABYLON.Matrix();
  91956. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91957. if (!_this.getScene().useRightHandedSystem) {
  91958. [2, 6, 8, 9, 14].forEach(function (num) {
  91959. if (_this._standingMatrix) {
  91960. _this._standingMatrix.m[num] *= -1;
  91961. }
  91962. });
  91963. }
  91964. callback(true);
  91965. }
  91966. });
  91967. };
  91968. /**
  91969. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91970. * @returns A promise with a boolean set to if the standing matrix is supported.
  91971. */
  91972. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91973. var _this = this;
  91974. return new Promise(function (res, rej) {
  91975. _this.useStandingMatrix(function (supported) {
  91976. res(supported);
  91977. });
  91978. });
  91979. };
  91980. /**
  91981. * Disposes the camera
  91982. */
  91983. WebVRFreeCamera.prototype.dispose = function () {
  91984. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91985. _super.prototype.dispose.call(this);
  91986. };
  91987. /**
  91988. * Gets a vrController by name.
  91989. * @param name The name of the controller to retreive
  91990. * @returns the controller matching the name specified or null if not found
  91991. */
  91992. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91993. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91994. var gp = _a[_i];
  91995. if (gp.hand === name) {
  91996. return gp;
  91997. }
  91998. }
  91999. return null;
  92000. };
  92001. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92002. /**
  92003. * The controller corrisponding to the users left hand.
  92004. */
  92005. get: function () {
  92006. if (!this._leftController) {
  92007. this._leftController = this.getControllerByName("left");
  92008. }
  92009. return this._leftController;
  92010. },
  92011. enumerable: true,
  92012. configurable: true
  92013. });
  92014. ;
  92015. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92016. /**
  92017. * The controller corrisponding to the users right hand.
  92018. */
  92019. get: function () {
  92020. if (!this._rightController) {
  92021. this._rightController = this.getControllerByName("right");
  92022. }
  92023. return this._rightController;
  92024. },
  92025. enumerable: true,
  92026. configurable: true
  92027. });
  92028. ;
  92029. /**
  92030. * Casts a ray forward from the vrCamera's gaze.
  92031. * @param length Length of the ray (default: 100)
  92032. * @returns the ray corrisponding to the gaze
  92033. */
  92034. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92035. if (length === void 0) { length = 100; }
  92036. if (this.leftCamera) {
  92037. // Use left eye to avoid computation to compute center on every call
  92038. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92039. }
  92040. else {
  92041. return _super.prototype.getForwardRay.call(this, length);
  92042. }
  92043. };
  92044. /**
  92045. * Updates the camera based on device's frame data
  92046. */
  92047. WebVRFreeCamera.prototype._checkInputs = function () {
  92048. if (this._vrDevice && this._vrDevice.isPresenting) {
  92049. this._vrDevice.getFrameData(this._frameData);
  92050. this.updateFromDevice(this._frameData.pose);
  92051. }
  92052. _super.prototype._checkInputs.call(this);
  92053. };
  92054. /**
  92055. * Updates the poseControlled values based on the input device pose.
  92056. * @param poseData Pose coming from the device
  92057. */
  92058. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92059. if (poseData && poseData.orientation) {
  92060. this.rawPose = poseData;
  92061. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92062. if (this.getScene().useRightHandedSystem) {
  92063. this._deviceRoomRotationQuaternion.z *= -1;
  92064. this._deviceRoomRotationQuaternion.w *= -1;
  92065. }
  92066. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92067. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92068. if (this.getScene().useRightHandedSystem) {
  92069. this._deviceRoomPosition.z *= -1;
  92070. }
  92071. }
  92072. this._poseSet = true;
  92073. }
  92074. };
  92075. /**
  92076. * WebVR's attach control will start broadcasting frames to the device.
  92077. * Note that in certain browsers (chrome for example) this function must be called
  92078. * within a user-interaction callback. Example:
  92079. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92080. *
  92081. * @param element html element to attach the vrDevice to
  92082. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92083. */
  92084. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92085. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92086. this._attached = true;
  92087. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92088. if (this._vrDevice) {
  92089. this.getEngine().enableVR();
  92090. }
  92091. };
  92092. /**
  92093. * Detaches the camera from the html element and disables VR
  92094. *
  92095. * @param element html element to detach from
  92096. */
  92097. WebVRFreeCamera.prototype.detachControl = function (element) {
  92098. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92099. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92100. _super.prototype.detachControl.call(this, element);
  92101. this._attached = false;
  92102. this.getEngine().disableVR();
  92103. };
  92104. /**
  92105. * @returns the name of this class
  92106. */
  92107. WebVRFreeCamera.prototype.getClassName = function () {
  92108. return "WebVRFreeCamera";
  92109. };
  92110. /**
  92111. * Calls resetPose on the vrDisplay
  92112. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92113. */
  92114. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92115. //uses the vrDisplay's "resetPose()".
  92116. //pitch and roll won't be affected.
  92117. this._vrDevice.resetPose();
  92118. };
  92119. /**
  92120. * Updates the rig cameras (left and right eye)
  92121. */
  92122. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92123. var camLeft = this._rigCameras[0];
  92124. var camRight = this._rigCameras[1];
  92125. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92126. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92127. camLeft.position.copyFrom(this._deviceRoomPosition);
  92128. camRight.position.copyFrom(this._deviceRoomPosition);
  92129. };
  92130. /**
  92131. * Updates the cached values of the camera
  92132. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92133. */
  92134. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92135. var _this = this;
  92136. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92137. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92138. if (!this.updateCacheCalled) {
  92139. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92140. this.updateCacheCalled = true;
  92141. this.update();
  92142. }
  92143. // Set working vector to the device position in room space rotated by the new rotation
  92144. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92145. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92146. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92147. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92148. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92149. // Add translation from anchor position
  92150. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92151. this._workingVector.addInPlace(this.position);
  92152. this._workingVector.subtractInPlace(this._cache.position);
  92153. this._deviceToWorld.setTranslation(this._workingVector);
  92154. // Set an inverted matrix to be used when updating the camera
  92155. this._deviceToWorld.invertToRef(this._worldToDevice);
  92156. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92157. this.controllers.forEach(function (controller) {
  92158. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92159. controller.update();
  92160. });
  92161. }
  92162. if (!ignoreParentClass) {
  92163. _super.prototype._updateCache.call(this);
  92164. }
  92165. this.updateCacheCalled = false;
  92166. };
  92167. /**
  92168. * Updates the current device position and rotation in the babylon world
  92169. */
  92170. WebVRFreeCamera.prototype.update = function () {
  92171. // Get current device position in babylon world
  92172. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92173. // Get current device rotation in babylon world
  92174. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92175. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92176. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92177. if (this._poseSet) {
  92178. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92179. }
  92180. _super.prototype.update.call(this);
  92181. };
  92182. /**
  92183. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92184. * @returns an identity matrix
  92185. */
  92186. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92187. return BABYLON.Matrix.Identity();
  92188. };
  92189. /**
  92190. * This function is called by the two RIG cameras.
  92191. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92192. */
  92193. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92194. var _this = this;
  92195. // Update the parent camera prior to using a child camera to avoid desynchronization
  92196. var parentCamera = this._cameraRigParams["parentCamera"];
  92197. parentCamera._updateCache();
  92198. //WebVR 1.1
  92199. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92200. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92201. if (!this.getScene().useRightHandedSystem) {
  92202. [2, 6, 8, 9, 14].forEach(function (num) {
  92203. _this._webvrViewMatrix.m[num] *= -1;
  92204. });
  92205. }
  92206. // update the camera rotation matrix
  92207. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92208. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92209. // Computing target and final matrix
  92210. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92211. // should the view matrix be updated with scale and position offset?
  92212. if (parentCamera.deviceScaleFactor !== 1) {
  92213. this._webvrViewMatrix.invert();
  92214. // scale the position, if set
  92215. if (parentCamera.deviceScaleFactor) {
  92216. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92217. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92218. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92219. }
  92220. this._webvrViewMatrix.invert();
  92221. }
  92222. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92223. // Compute global position
  92224. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92225. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92226. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92227. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92228. this._markSyncedWithParent();
  92229. return this._webvrViewMatrix;
  92230. };
  92231. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92232. var _this = this;
  92233. var parentCamera = this.parent;
  92234. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92235. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92236. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92237. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92238. //babylon compatible matrix
  92239. if (!this.getScene().useRightHandedSystem) {
  92240. [8, 9, 10, 11].forEach(function (num) {
  92241. _this._projectionMatrix.m[num] *= -1;
  92242. });
  92243. }
  92244. return this._projectionMatrix;
  92245. };
  92246. /**
  92247. * Initializes the controllers and their meshes
  92248. */
  92249. WebVRFreeCamera.prototype.initControllers = function () {
  92250. var _this = this;
  92251. this.controllers = [];
  92252. var manager = this.getScene().gamepadManager;
  92253. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  92254. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92255. var webVrController = gamepad;
  92256. if (webVrController.defaultModel) {
  92257. webVrController.defaultModel.setEnabled(false);
  92258. }
  92259. if (webVrController.hand === "right") {
  92260. _this._rightController = null;
  92261. }
  92262. if (webVrController.hand === "left") {
  92263. _this._leftController = null;
  92264. }
  92265. var controllerIndex = _this.controllers.indexOf(webVrController);
  92266. if (controllerIndex !== -1) {
  92267. _this.controllers.splice(controllerIndex, 1);
  92268. }
  92269. }
  92270. });
  92271. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  92272. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  92273. var webVrController_1 = gamepad;
  92274. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  92275. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  92276. if (_this.webVROptions.controllerMeshes) {
  92277. if (webVrController_1.defaultModel) {
  92278. webVrController_1.defaultModel.setEnabled(true);
  92279. }
  92280. else {
  92281. // Load the meshes
  92282. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  92283. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  92284. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  92285. if (_this.webVROptions.defaultLightingOnControllers) {
  92286. if (!_this._lightOnControllers) {
  92287. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  92288. }
  92289. var activateLightOnSubMeshes_1 = function (mesh, light) {
  92290. var children = mesh.getChildren();
  92291. if (children.length !== 0) {
  92292. children.forEach(function (mesh) {
  92293. light.includedOnlyMeshes.push(mesh);
  92294. activateLightOnSubMeshes_1(mesh, light);
  92295. });
  92296. }
  92297. };
  92298. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  92299. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  92300. }
  92301. });
  92302. }
  92303. }
  92304. webVrController_1.attachToPoseControlledCamera(_this);
  92305. // since this is async - sanity check. Is the controller already stored?
  92306. if (_this.controllers.indexOf(webVrController_1) === -1) {
  92307. //add to the controllers array
  92308. _this.controllers.push(webVrController_1);
  92309. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  92310. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  92311. // So we're overriding setting left & right manually to be sure
  92312. var firstViveWandDetected = false;
  92313. for (var i = 0; i < _this.controllers.length; i++) {
  92314. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92315. if (!firstViveWandDetected) {
  92316. firstViveWandDetected = true;
  92317. _this.controllers[i].hand = "left";
  92318. }
  92319. else {
  92320. _this.controllers[i].hand = "right";
  92321. }
  92322. }
  92323. }
  92324. //did we find enough controllers? Great! let the developer know.
  92325. if (_this.controllers.length >= 2) {
  92326. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  92327. }
  92328. }
  92329. }
  92330. });
  92331. };
  92332. return WebVRFreeCamera;
  92333. }(BABYLON.FreeCamera));
  92334. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92335. })(BABYLON || (BABYLON = {}));
  92336. //# sourceMappingURL=babylon.webVRCamera.js.map
  92337. var BABYLON;
  92338. (function (BABYLON) {
  92339. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  92340. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  92341. });
  92342. // We're mainly based on the logic defined into the FreeCamera code
  92343. /**
  92344. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92345. * being tilted forward or back and left or right.
  92346. */
  92347. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92348. __extends(DeviceOrientationCamera, _super);
  92349. /**
  92350. * Creates a new device orientation camera
  92351. * @param name The name of the camera
  92352. * @param position The start position camera
  92353. * @param scene The scene the camera belongs to
  92354. */
  92355. function DeviceOrientationCamera(name, position, scene) {
  92356. var _this = _super.call(this, name, position, scene) || this;
  92357. _this._quaternionCache = new BABYLON.Quaternion();
  92358. _this.inputs.addDeviceOrientation();
  92359. return _this;
  92360. }
  92361. /**
  92362. * Gets the current instance class name ("DeviceOrientationCamera").
  92363. * This helps avoiding instanceof at run time.
  92364. * @returns the class name
  92365. */
  92366. DeviceOrientationCamera.prototype.getClassName = function () {
  92367. return "DeviceOrientationCamera";
  92368. };
  92369. /**
  92370. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92371. */
  92372. DeviceOrientationCamera.prototype._checkInputs = function () {
  92373. _super.prototype._checkInputs.call(this);
  92374. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92375. if (this._initialQuaternion) {
  92376. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92377. }
  92378. };
  92379. /**
  92380. * Reset the camera to its default orientation on the specified axis only.
  92381. * @param axis The axis to reset
  92382. */
  92383. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92384. var _this = this;
  92385. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92386. //can only work if this camera has a rotation quaternion already.
  92387. if (!this.rotationQuaternion)
  92388. return;
  92389. if (!this._initialQuaternion) {
  92390. this._initialQuaternion = new BABYLON.Quaternion();
  92391. }
  92392. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92393. ['x', 'y', 'z'].forEach(function (axisName) {
  92394. if (!axis[axisName]) {
  92395. _this._initialQuaternion[axisName] = 0;
  92396. }
  92397. else {
  92398. _this._initialQuaternion[axisName] *= -1;
  92399. }
  92400. });
  92401. this._initialQuaternion.normalize();
  92402. //force rotation update
  92403. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92404. };
  92405. return DeviceOrientationCamera;
  92406. }(BABYLON.FreeCamera));
  92407. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92408. })(BABYLON || (BABYLON = {}));
  92409. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92410. var BABYLON;
  92411. (function (BABYLON) {
  92412. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92413. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92414. });
  92415. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92416. __extends(VRDeviceOrientationFreeCamera, _super);
  92417. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92418. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92419. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92420. var _this = _super.call(this, name, position, scene) || this;
  92421. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92422. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92423. return _this;
  92424. }
  92425. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92426. return "VRDeviceOrientationFreeCamera";
  92427. };
  92428. return VRDeviceOrientationFreeCamera;
  92429. }(BABYLON.DeviceOrientationCamera));
  92430. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92431. })(BABYLON || (BABYLON = {}));
  92432. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  92433. var BABYLON;
  92434. (function (BABYLON) {
  92435. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  92436. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  92437. });
  92438. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92439. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92440. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92441. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92442. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92443. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92444. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92445. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92446. _this.inputs.addVRDeviceOrientation();
  92447. return _this;
  92448. }
  92449. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92450. return "VRDeviceOrientationArcRotateCamera";
  92451. };
  92452. return VRDeviceOrientationArcRotateCamera;
  92453. }(BABYLON.ArcRotateCamera));
  92454. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92455. })(BABYLON || (BABYLON = {}));
  92456. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  92457. var BABYLON;
  92458. (function (BABYLON) {
  92459. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  92460. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  92461. });
  92462. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92463. __extends(VRDeviceOrientationGamepadCamera, _super);
  92464. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92465. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92466. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92467. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92468. _this.inputs.addGamepad();
  92469. return _this;
  92470. }
  92471. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92472. return "VRDeviceOrientationGamepadCamera";
  92473. };
  92474. return VRDeviceOrientationGamepadCamera;
  92475. }(BABYLON.VRDeviceOrientationFreeCamera));
  92476. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92477. })(BABYLON || (BABYLON = {}));
  92478. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  92479. var BABYLON;
  92480. (function (BABYLON) {
  92481. var VRExperienceHelperGazer = /** @class */ (function () {
  92482. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92483. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92484. this.scene = scene;
  92485. this._pointerDownOnMeshAsked = false;
  92486. this._isActionableMesh = false;
  92487. this._teleportationRequestInitiated = false;
  92488. this._teleportationBackRequestInitiated = false;
  92489. this._rotationRightAsked = false;
  92490. this._rotationLeftAsked = false;
  92491. this._dpadPressed = true;
  92492. this._activePointer = false;
  92493. this._id = VRExperienceHelperGazer._idCounter++;
  92494. // Gaze tracker
  92495. if (!gazeTrackerToClone) {
  92496. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92497. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92498. this._gazeTracker.isPickable = false;
  92499. this._gazeTracker.isVisible = false;
  92500. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92501. targetMat.specularColor = BABYLON.Color3.Black();
  92502. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92503. targetMat.backFaceCulling = false;
  92504. this._gazeTracker.material = targetMat;
  92505. }
  92506. else {
  92507. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92508. }
  92509. }
  92510. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92511. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92512. };
  92513. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92514. this._pointerDownOnMeshAsked = true;
  92515. if (this._currentHit) {
  92516. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92517. }
  92518. };
  92519. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92520. if (this._currentHit) {
  92521. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92522. }
  92523. this._pointerDownOnMeshAsked = false;
  92524. };
  92525. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92526. this._activePointer = true;
  92527. };
  92528. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92529. this._activePointer = false;
  92530. };
  92531. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92532. if (distance === void 0) { distance = 100; }
  92533. };
  92534. VRExperienceHelperGazer.prototype.dispose = function () {
  92535. this._interactionsEnabled = false;
  92536. this._teleportationEnabled = false;
  92537. if (this._gazeTracker) {
  92538. this._gazeTracker.dispose();
  92539. }
  92540. };
  92541. VRExperienceHelperGazer._idCounter = 0;
  92542. return VRExperienceHelperGazer;
  92543. }());
  92544. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92545. __extends(VRExperienceHelperControllerGazer, _super);
  92546. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92547. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92548. _this.webVRController = webVRController;
  92549. // Laser pointer
  92550. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92551. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92552. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92553. laserPointerMaterial.alpha = 0.6;
  92554. _this._laserPointer.material = laserPointerMaterial;
  92555. _this._laserPointer.rotation.x = Math.PI / 2;
  92556. _this._laserPointer.position.z = -0.5;
  92557. _this._laserPointer.isVisible = false;
  92558. _this._laserPointer.isPickable = false;
  92559. if (!webVRController.mesh) {
  92560. // Create an empty mesh that is used prior to loading the high quality model
  92561. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92562. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92563. preloadPointerPose.rotation.x = -0.7;
  92564. preloadMesh.addChild(preloadPointerPose);
  92565. webVRController.attachToMesh(preloadMesh);
  92566. }
  92567. _this._setLaserPointerParent(webVRController.mesh);
  92568. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92569. _this._setLaserPointerParent(mesh);
  92570. });
  92571. return _this;
  92572. }
  92573. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92574. return this.webVRController.getForwardRay(length);
  92575. };
  92576. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92577. _super.prototype._activatePointer.call(this);
  92578. this._laserPointer.isVisible = true;
  92579. };
  92580. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92581. _super.prototype._deactivatePointer.call(this);
  92582. this._laserPointer.isVisible = false;
  92583. };
  92584. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92585. this._laserPointer.material.emissiveColor = color;
  92586. };
  92587. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92588. var makeNotPick = function (root) {
  92589. root.name += " laserPointer";
  92590. root.isPickable = false;
  92591. root.getChildMeshes().forEach(function (c) {
  92592. makeNotPick(c);
  92593. });
  92594. };
  92595. makeNotPick(mesh);
  92596. var childMeshes = mesh.getChildMeshes();
  92597. this.webVRController._pointingPoseNode = null;
  92598. for (var i = 0; i < childMeshes.length; i++) {
  92599. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92600. mesh = childMeshes[i];
  92601. this.webVRController._pointingPoseNode = mesh;
  92602. break;
  92603. }
  92604. }
  92605. this._laserPointer.parent = mesh;
  92606. };
  92607. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92608. if (distance === void 0) { distance = 100; }
  92609. this._laserPointer.scaling.y = distance;
  92610. this._laserPointer.position.z = -distance / 2;
  92611. };
  92612. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92613. _super.prototype.dispose.call(this);
  92614. this._laserPointer.dispose();
  92615. if (this._meshAttachedObserver) {
  92616. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92617. }
  92618. };
  92619. return VRExperienceHelperControllerGazer;
  92620. }(VRExperienceHelperGazer));
  92621. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92622. __extends(VRExperienceHelperCameraGazer, _super);
  92623. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92624. var _this = _super.call(this, scene) || this;
  92625. _this.getCamera = getCamera;
  92626. return _this;
  92627. }
  92628. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92629. var camera = this.getCamera();
  92630. if (camera) {
  92631. return camera.getForwardRay(length);
  92632. }
  92633. else {
  92634. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92635. }
  92636. };
  92637. return VRExperienceHelperCameraGazer;
  92638. }(VRExperienceHelperGazer));
  92639. /**
  92640. * Helps to quickly add VR support to an existing scene.
  92641. * See http://doc.babylonjs.com/how_to/webvr_helper
  92642. */
  92643. var VRExperienceHelper = /** @class */ (function () {
  92644. /**
  92645. * Instantiates a VRExperienceHelper.
  92646. * Helps to quickly add VR support to an existing scene.
  92647. * @param scene The scene the VRExperienceHelper belongs to.
  92648. * @param webVROptions Options to modify the vr experience helper's behavior.
  92649. */
  92650. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92651. if (webVROptions === void 0) { webVROptions = {}; }
  92652. var _this = this;
  92653. this.webVROptions = webVROptions;
  92654. // Can the system support WebVR, even if a headset isn't plugged in?
  92655. this._webVRsupported = false;
  92656. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92657. this._webVRready = false;
  92658. // Are we waiting for the requestPresent callback to complete?
  92659. this._webVRrequesting = false;
  92660. // Are we presenting to the headset right now?
  92661. this._webVRpresenting = false;
  92662. // Are we presenting in the fullscreen fallback?
  92663. this._fullscreenVRpresenting = false;
  92664. /**
  92665. * Observable raised when entering VR.
  92666. */
  92667. this.onEnteringVRObservable = new BABYLON.Observable();
  92668. /**
  92669. * Observable raised when exiting VR.
  92670. */
  92671. this.onExitingVRObservable = new BABYLON.Observable();
  92672. /**
  92673. * Observable raised when controller mesh is loaded.
  92674. */
  92675. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92676. this._useCustomVRButton = false;
  92677. this._teleportationRequested = false;
  92678. this._teleportActive = false;
  92679. this._floorMeshesCollection = [];
  92680. this._rotationAllowed = true;
  92681. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92682. this._isDefaultTeleportationTarget = true;
  92683. this._teleportationFillColor = "#444444";
  92684. this._teleportationBorderColor = "#FFFFFF";
  92685. this._rotationAngle = 0;
  92686. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92687. this._padSensibilityUp = 0.65;
  92688. this._padSensibilityDown = 0.35;
  92689. this.leftController = null;
  92690. this.rightController = null;
  92691. /**
  92692. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92693. */
  92694. this.onNewMeshSelected = new BABYLON.Observable();
  92695. /**
  92696. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92697. */
  92698. this.onNewMeshPicked = new BABYLON.Observable();
  92699. /**
  92700. * Observable raised before camera teleportation
  92701. */
  92702. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92703. /**
  92704. * Observable raised after camera teleportation
  92705. */
  92706. this.onAfterCameraTeleport = new BABYLON.Observable();
  92707. /**
  92708. * Observable raised when current selected mesh gets unselected
  92709. */
  92710. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92711. /**
  92712. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92713. */
  92714. this.teleportationEnabled = true;
  92715. this._teleportationInitialized = false;
  92716. this._interactionsEnabled = false;
  92717. this._interactionsRequested = false;
  92718. this._displayGaze = true;
  92719. this._displayLaserPointer = true;
  92720. this._onResize = function () {
  92721. _this.moveButtonToBottomRight();
  92722. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92723. _this.exitVR();
  92724. }
  92725. };
  92726. this._onFullscreenChange = function () {
  92727. if (document.fullscreen !== undefined) {
  92728. _this._fullscreenVRpresenting = document.fullscreen;
  92729. }
  92730. else if (document.mozFullScreen !== undefined) {
  92731. _this._fullscreenVRpresenting = document.mozFullScreen;
  92732. }
  92733. else if (document.webkitIsFullScreen !== undefined) {
  92734. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92735. }
  92736. else if (document.msIsFullScreen !== undefined) {
  92737. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92738. }
  92739. else if (document.msFullscreenElement !== undefined) {
  92740. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92741. }
  92742. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92743. _this.exitVR();
  92744. if (!_this._useCustomVRButton) {
  92745. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92746. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92747. }
  92748. }
  92749. };
  92750. this.beforeRender = function () {
  92751. if (_this.leftController && _this.leftController._activePointer) {
  92752. _this._castRayAndSelectObject(_this.leftController);
  92753. }
  92754. if (_this.rightController && _this.rightController._activePointer) {
  92755. _this._castRayAndSelectObject(_this.rightController);
  92756. }
  92757. if (_this._noControllerIsActive) {
  92758. _this._castRayAndSelectObject(_this._cameraGazer);
  92759. }
  92760. else {
  92761. _this._cameraGazer._gazeTracker.isVisible = false;
  92762. }
  92763. };
  92764. this._onNewGamepadConnected = function (gamepad) {
  92765. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92766. if (gamepad.leftStick) {
  92767. gamepad.onleftstickchanged(function (stickValues) {
  92768. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92769. // Listening to classic/xbox gamepad only if no VR controller is active
  92770. if ((!_this.leftController && !_this.rightController) ||
  92771. ((_this.leftController && !_this.leftController._activePointer) &&
  92772. (_this.rightController && !_this.rightController._activePointer))) {
  92773. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92774. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92775. }
  92776. }
  92777. });
  92778. }
  92779. if (gamepad.rightStick) {
  92780. gamepad.onrightstickchanged(function (stickValues) {
  92781. if (_this._teleportationInitialized) {
  92782. _this._checkRotate(stickValues, _this._cameraGazer);
  92783. }
  92784. });
  92785. }
  92786. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92787. gamepad.onbuttondown(function (buttonPressed) {
  92788. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92789. _this._cameraGazer._selectionPointerDown();
  92790. }
  92791. });
  92792. gamepad.onbuttonup(function (buttonPressed) {
  92793. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92794. _this._cameraGazer._selectionPointerUp();
  92795. }
  92796. });
  92797. }
  92798. }
  92799. else {
  92800. var webVRController = gamepad;
  92801. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92802. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92803. _this.rightController = controller;
  92804. }
  92805. else {
  92806. _this.leftController = controller;
  92807. }
  92808. _this._tryEnableInteractionOnController(controller);
  92809. }
  92810. };
  92811. // 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
  92812. this._tryEnableInteractionOnController = function (controller) {
  92813. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92814. _this._enableInteractionOnController(controller);
  92815. }
  92816. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92817. _this._enableTeleportationOnController(controller);
  92818. }
  92819. };
  92820. this._onNewGamepadDisconnected = function (gamepad) {
  92821. if (gamepad instanceof BABYLON.WebVRController) {
  92822. if (gamepad.hand === "left" && _this.leftController != null) {
  92823. _this.leftController.dispose();
  92824. _this.leftController = null;
  92825. }
  92826. if (gamepad.hand === "right" && _this.rightController != null) {
  92827. _this.rightController.dispose();
  92828. _this.rightController = null;
  92829. }
  92830. }
  92831. };
  92832. this._workingVector = BABYLON.Vector3.Zero();
  92833. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92834. this._workingMatrix = BABYLON.Matrix.Identity();
  92835. this._scene = scene;
  92836. this._canvas = scene.getEngine().getRenderingCanvas();
  92837. // Parse options
  92838. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92839. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92840. }
  92841. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92842. webVROptions.createDeviceOrientationCamera = true;
  92843. }
  92844. if (webVROptions.laserToggle === undefined) {
  92845. webVROptions.laserToggle = true;
  92846. }
  92847. if (webVROptions.defaultHeight === undefined) {
  92848. webVROptions.defaultHeight = 1.7;
  92849. }
  92850. if (webVROptions.useCustomVRButton) {
  92851. this._useCustomVRButton = true;
  92852. if (webVROptions.customVRButton) {
  92853. this._btnVR = webVROptions.customVRButton;
  92854. }
  92855. }
  92856. if (webVROptions.rayLength) {
  92857. this._rayLength = webVROptions.rayLength;
  92858. }
  92859. this._defaultHeight = webVROptions.defaultHeight;
  92860. if (webVROptions.positionScale) {
  92861. this._rayLength *= webVROptions.positionScale;
  92862. this._defaultHeight *= webVROptions.positionScale;
  92863. }
  92864. // Set position
  92865. if (this._scene.activeCamera) {
  92866. this._position = this._scene.activeCamera.position.clone();
  92867. }
  92868. else {
  92869. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92870. }
  92871. // Set non-vr camera
  92872. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92873. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92874. // Copy data from existing camera
  92875. if (this._scene.activeCamera) {
  92876. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92877. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92878. // Set rotation from previous camera
  92879. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92880. var targetCamera = this._scene.activeCamera;
  92881. if (targetCamera.rotationQuaternion) {
  92882. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92883. }
  92884. else {
  92885. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92886. }
  92887. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92888. }
  92889. }
  92890. this._scene.activeCamera = this._deviceOrientationCamera;
  92891. if (this._canvas) {
  92892. this._scene.activeCamera.attachControl(this._canvas);
  92893. }
  92894. }
  92895. else {
  92896. this._existingCamera = this._scene.activeCamera;
  92897. }
  92898. // Create VR cameras
  92899. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92900. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92901. }
  92902. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92903. this._webVRCamera.useStandingMatrix();
  92904. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92905. // Create default button
  92906. if (!this._useCustomVRButton) {
  92907. this._btnVR = document.createElement("BUTTON");
  92908. this._btnVR.className = "babylonVRicon";
  92909. this._btnVR.id = "babylonVRiconbtn";
  92910. this._btnVR.title = "Click to switch to VR";
  92911. 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) }";
  92912. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92913. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92914. // css += ".babylonVRicon.vrdisplaysupported { }";
  92915. // css += ".babylonVRicon.vrdisplayready { }";
  92916. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92917. var style = document.createElement('style');
  92918. style.appendChild(document.createTextNode(css));
  92919. document.getElementsByTagName('head')[0].appendChild(style);
  92920. this.moveButtonToBottomRight();
  92921. }
  92922. // VR button click event
  92923. if (this._btnVR) {
  92924. this._btnVR.addEventListener("click", function () {
  92925. if (!_this.isInVRMode) {
  92926. _this.enterVR();
  92927. }
  92928. else {
  92929. _this.exitVR();
  92930. }
  92931. });
  92932. }
  92933. // Window events
  92934. window.addEventListener("resize", this._onResize);
  92935. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92936. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92937. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92938. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92939. document.onmsfullscreenchange = this._onFullscreenChange;
  92940. // Display vr button when headset is connected
  92941. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92942. this.displayVRButton();
  92943. }
  92944. else {
  92945. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92946. if (e.vrDisplay) {
  92947. _this.displayVRButton();
  92948. }
  92949. });
  92950. }
  92951. // Exiting VR mode using 'ESC' key on desktop
  92952. this._onKeyDown = function (event) {
  92953. if (event.keyCode === 27 && _this.isInVRMode) {
  92954. _this.exitVR();
  92955. }
  92956. };
  92957. document.addEventListener("keydown", this._onKeyDown);
  92958. // Exiting VR mode double tapping the touch screen
  92959. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92960. if (_this.isInVRMode) {
  92961. _this.exitVR();
  92962. if (_this._fullscreenVRpresenting) {
  92963. _this._scene.getEngine().switchFullscreen(true);
  92964. }
  92965. }
  92966. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92967. // Listen for WebVR display changes
  92968. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92969. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92970. this._onVRRequestPresentStart = function () {
  92971. _this._webVRrequesting = true;
  92972. _this.updateButtonVisibility();
  92973. };
  92974. this._onVRRequestPresentComplete = function (success) {
  92975. _this._webVRrequesting = false;
  92976. _this.updateButtonVisibility();
  92977. };
  92978. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92979. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92980. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92981. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92982. scene.onDisposeObservable.add(function () {
  92983. _this.dispose();
  92984. });
  92985. // Gamepad connection events
  92986. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92987. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92988. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92989. this.updateButtonVisibility();
  92990. //create easing functions
  92991. this._circleEase = new BABYLON.CircleEase();
  92992. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92993. if (this.webVROptions.floorMeshes) {
  92994. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92995. }
  92996. }
  92997. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92998. /** Return this.onEnteringVRObservable
  92999. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93000. */
  93001. get: function () {
  93002. return this.onEnteringVRObservable;
  93003. },
  93004. enumerable: true,
  93005. configurable: true
  93006. });
  93007. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93008. /** Return this.onExitingVRObservable
  93009. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93010. */
  93011. get: function () {
  93012. return this.onExitingVRObservable;
  93013. },
  93014. enumerable: true,
  93015. configurable: true
  93016. });
  93017. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93018. /** Return this.onControllerMeshLoadedObservable
  93019. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93020. */
  93021. get: function () {
  93022. return this.onControllerMeshLoadedObservable;
  93023. },
  93024. enumerable: true,
  93025. configurable: true
  93026. });
  93027. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93028. /**
  93029. * The mesh used to display where the user is going to teleport.
  93030. */
  93031. get: function () {
  93032. return this._teleportationTarget;
  93033. },
  93034. /**
  93035. * Sets the mesh to be used to display where the user is going to teleport.
  93036. */
  93037. set: function (value) {
  93038. if (value) {
  93039. value.name = "teleportationTarget";
  93040. this._isDefaultTeleportationTarget = false;
  93041. this._teleportationTarget = value;
  93042. }
  93043. },
  93044. enumerable: true,
  93045. configurable: true
  93046. });
  93047. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93048. /**
  93049. * The mesh used to display where the user is selecting,
  93050. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93051. * See http://doc.babylonjs.com/resources/baking_transformations
  93052. */
  93053. get: function () {
  93054. return this._cameraGazer._gazeTracker;
  93055. },
  93056. set: function (value) {
  93057. if (value) {
  93058. this._cameraGazer._gazeTracker = value;
  93059. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93060. this._cameraGazer._gazeTracker.isPickable = false;
  93061. this._cameraGazer._gazeTracker.isVisible = false;
  93062. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93063. if (this.leftController) {
  93064. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93065. }
  93066. if (this.rightController) {
  93067. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93068. }
  93069. }
  93070. },
  93071. enumerable: true,
  93072. configurable: true
  93073. });
  93074. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93075. /**
  93076. * If the ray of the gaze should be displayed.
  93077. */
  93078. get: function () {
  93079. return this._displayGaze;
  93080. },
  93081. /**
  93082. * Sets if the ray of the gaze should be displayed.
  93083. */
  93084. set: function (value) {
  93085. this._displayGaze = value;
  93086. if (!value) {
  93087. this._cameraGazer._gazeTracker.isVisible = false;
  93088. if (this.leftController) {
  93089. this.leftController._gazeTracker.isVisible = false;
  93090. }
  93091. if (this.rightController) {
  93092. this.rightController._gazeTracker.isVisible = false;
  93093. }
  93094. }
  93095. },
  93096. enumerable: true,
  93097. configurable: true
  93098. });
  93099. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93100. /**
  93101. * If the ray of the LaserPointer should be displayed.
  93102. */
  93103. get: function () {
  93104. return this._displayLaserPointer;
  93105. },
  93106. /**
  93107. * Sets if the ray of the LaserPointer should be displayed.
  93108. */
  93109. set: function (value) {
  93110. this._displayLaserPointer = value;
  93111. if (!value) {
  93112. if (this.rightController) {
  93113. this.rightController._deactivatePointer();
  93114. this.rightController._gazeTracker.isVisible = false;
  93115. }
  93116. if (this.leftController) {
  93117. this.leftController._deactivatePointer();
  93118. this.leftController._gazeTracker.isVisible = false;
  93119. }
  93120. }
  93121. else {
  93122. if (this.rightController) {
  93123. this.rightController._activatePointer();
  93124. }
  93125. if (this.leftController) {
  93126. this.leftController._activatePointer();
  93127. }
  93128. }
  93129. },
  93130. enumerable: true,
  93131. configurable: true
  93132. });
  93133. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93134. /**
  93135. * The deviceOrientationCamera used as the camera when not in VR.
  93136. */
  93137. get: function () {
  93138. return this._deviceOrientationCamera;
  93139. },
  93140. enumerable: true,
  93141. configurable: true
  93142. });
  93143. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93144. /**
  93145. * Based on the current WebVR support, returns the current VR camera used.
  93146. */
  93147. get: function () {
  93148. if (this._webVRready) {
  93149. return this._webVRCamera;
  93150. }
  93151. else {
  93152. return this._scene.activeCamera;
  93153. }
  93154. },
  93155. enumerable: true,
  93156. configurable: true
  93157. });
  93158. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93159. /**
  93160. * The webVRCamera which is used when in VR.
  93161. */
  93162. get: function () {
  93163. return this._webVRCamera;
  93164. },
  93165. enumerable: true,
  93166. configurable: true
  93167. });
  93168. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93169. /**
  93170. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93171. */
  93172. get: function () {
  93173. return this._vrDeviceOrientationCamera;
  93174. },
  93175. enumerable: true,
  93176. configurable: true
  93177. });
  93178. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93179. get: function () {
  93180. var result = this._cameraGazer._teleportationRequestInitiated
  93181. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93182. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93183. return result;
  93184. },
  93185. enumerable: true,
  93186. configurable: true
  93187. });
  93188. // Raised when one of the controller has loaded successfully its associated default mesh
  93189. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93190. if (this.leftController && this.leftController.webVRController == webVRController) {
  93191. if (webVRController.mesh) {
  93192. this.leftController._setLaserPointerParent(webVRController.mesh);
  93193. }
  93194. }
  93195. if (this.rightController && this.rightController.webVRController == webVRController) {
  93196. if (webVRController.mesh) {
  93197. this.rightController._setLaserPointerParent(webVRController.mesh);
  93198. }
  93199. }
  93200. try {
  93201. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93202. }
  93203. catch (err) {
  93204. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93205. }
  93206. };
  93207. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93208. /**
  93209. * Gets a value indicating if we are currently in VR mode.
  93210. */
  93211. get: function () {
  93212. return this._webVRpresenting || this._fullscreenVRpresenting;
  93213. },
  93214. enumerable: true,
  93215. configurable: true
  93216. });
  93217. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93218. var vrDisplay = this._scene.getEngine().getVRDevice();
  93219. if (vrDisplay) {
  93220. var wasPresenting = this._webVRpresenting;
  93221. // A VR display is connected
  93222. this._webVRpresenting = vrDisplay.isPresenting;
  93223. if (wasPresenting && !this._webVRpresenting)
  93224. this.exitVR();
  93225. }
  93226. else {
  93227. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93228. }
  93229. this.updateButtonVisibility();
  93230. };
  93231. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93232. this._webVRsupported = eventArgs.vrSupported;
  93233. this._webVRready = !!eventArgs.vrDisplay;
  93234. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93235. this.updateButtonVisibility();
  93236. };
  93237. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93238. if (this._canvas && !this._useCustomVRButton) {
  93239. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93240. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93241. }
  93242. };
  93243. VRExperienceHelper.prototype.displayVRButton = function () {
  93244. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93245. document.body.appendChild(this._btnVR);
  93246. this._btnVRDisplayed = true;
  93247. }
  93248. };
  93249. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93250. if (!this._btnVR || this._useCustomVRButton) {
  93251. return;
  93252. }
  93253. this._btnVR.className = "babylonVRicon";
  93254. if (this.isInVRMode) {
  93255. this._btnVR.className += " vrdisplaypresenting";
  93256. }
  93257. else {
  93258. if (this._webVRready)
  93259. this._btnVR.className += " vrdisplayready";
  93260. if (this._webVRsupported)
  93261. this._btnVR.className += " vrdisplaysupported";
  93262. if (this._webVRrequesting)
  93263. this._btnVR.className += " vrdisplayrequesting";
  93264. }
  93265. };
  93266. /**
  93267. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93268. * Otherwise, will use the fullscreen API.
  93269. */
  93270. VRExperienceHelper.prototype.enterVR = function () {
  93271. if (this.onEnteringVRObservable) {
  93272. try {
  93273. this.onEnteringVRObservable.notifyObservers(this);
  93274. }
  93275. catch (err) {
  93276. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93277. }
  93278. }
  93279. if (this._scene.activeCamera) {
  93280. this._position = this._scene.activeCamera.position.clone();
  93281. // make sure that we return to the last active camera
  93282. this._existingCamera = this._scene.activeCamera;
  93283. }
  93284. if (this._webVRrequesting)
  93285. return;
  93286. // If WebVR is supported and a headset is connected
  93287. if (this._webVRready) {
  93288. if (!this._webVRpresenting) {
  93289. this._webVRCamera.position = this._position;
  93290. this._scene.activeCamera = this._webVRCamera;
  93291. }
  93292. }
  93293. else if (this._vrDeviceOrientationCamera) {
  93294. this._vrDeviceOrientationCamera.position = this._position;
  93295. if (this._scene.activeCamera) {
  93296. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93297. }
  93298. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93299. this._scene.getEngine().switchFullscreen(true);
  93300. this.updateButtonVisibility();
  93301. }
  93302. if (this._scene.activeCamera && this._canvas) {
  93303. this._scene.activeCamera.attachControl(this._canvas);
  93304. }
  93305. if (this._interactionsEnabled) {
  93306. this._scene.registerBeforeRender(this.beforeRender);
  93307. }
  93308. };
  93309. /**
  93310. * Attempt to exit VR, or fullscreen.
  93311. */
  93312. VRExperienceHelper.prototype.exitVR = function () {
  93313. if (this.onExitingVRObservable) {
  93314. try {
  93315. this.onExitingVRObservable.notifyObservers(this);
  93316. }
  93317. catch (err) {
  93318. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93319. }
  93320. }
  93321. if (this._webVRpresenting) {
  93322. this._scene.getEngine().disableVR();
  93323. }
  93324. if (this._scene.activeCamera) {
  93325. this._position = this._scene.activeCamera.position.clone();
  93326. }
  93327. if (this._deviceOrientationCamera) {
  93328. this._deviceOrientationCamera.position = this._position;
  93329. this._scene.activeCamera = this._deviceOrientationCamera;
  93330. if (this._canvas) {
  93331. this._scene.activeCamera.attachControl(this._canvas);
  93332. }
  93333. }
  93334. else if (this._existingCamera) {
  93335. this._existingCamera.position = this._position;
  93336. this._scene.activeCamera = this._existingCamera;
  93337. }
  93338. this.updateButtonVisibility();
  93339. if (this._interactionsEnabled) {
  93340. this._scene.unregisterBeforeRender(this.beforeRender);
  93341. }
  93342. // resize to update width and height when exiting vr exits fullscreen
  93343. this._scene.getEngine().resize();
  93344. };
  93345. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93346. /**
  93347. * The position of the vr experience helper.
  93348. */
  93349. get: function () {
  93350. return this._position;
  93351. },
  93352. /**
  93353. * Sets the position of the vr experience helper.
  93354. */
  93355. set: function (value) {
  93356. this._position = value;
  93357. if (this._scene.activeCamera) {
  93358. this._scene.activeCamera.position = value;
  93359. }
  93360. },
  93361. enumerable: true,
  93362. configurable: true
  93363. });
  93364. /**
  93365. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  93366. */
  93367. VRExperienceHelper.prototype.enableInteractions = function () {
  93368. var _this = this;
  93369. if (!this._interactionsEnabled) {
  93370. this._interactionsRequested = true;
  93371. if (this.leftController) {
  93372. this._enableInteractionOnController(this.leftController);
  93373. }
  93374. if (this.rightController) {
  93375. this._enableInteractionOnController(this.rightController);
  93376. }
  93377. this.raySelectionPredicate = function (mesh) {
  93378. return mesh.isVisible && mesh.isPickable;
  93379. };
  93380. this.meshSelectionPredicate = function (mesh) {
  93381. return true;
  93382. };
  93383. this._raySelectionPredicate = function (mesh) {
  93384. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93385. && mesh.name.indexOf("teleportationTarget") === -1
  93386. && mesh.name.indexOf("torusTeleportation") === -1
  93387. && mesh.name.indexOf("laserPointer") === -1)) {
  93388. return _this.raySelectionPredicate(mesh);
  93389. }
  93390. return false;
  93391. };
  93392. this._interactionsEnabled = true;
  93393. }
  93394. };
  93395. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93396. get: function () {
  93397. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93398. },
  93399. enumerable: true,
  93400. configurable: true
  93401. });
  93402. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93403. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93404. if (this._floorMeshesCollection[i].id === mesh.id) {
  93405. return true;
  93406. }
  93407. }
  93408. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93409. return true;
  93410. }
  93411. return false;
  93412. };
  93413. /**
  93414. * Adds a floor mesh to be used for teleportation.
  93415. * @param floorMesh the mesh to be used for teleportation.
  93416. */
  93417. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93418. if (!this._floorMeshesCollection) {
  93419. return;
  93420. }
  93421. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93422. return;
  93423. }
  93424. this._floorMeshesCollection.push(floorMesh);
  93425. };
  93426. /**
  93427. * Removes a floor mesh from being used for teleportation.
  93428. * @param floorMesh the mesh to be removed.
  93429. */
  93430. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93431. if (!this._floorMeshesCollection) {
  93432. return;
  93433. }
  93434. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93435. if (meshIndex !== -1) {
  93436. this._floorMeshesCollection.splice(meshIndex, 1);
  93437. }
  93438. };
  93439. /**
  93440. * Enables interactions and teleportation using the VR controllers and gaze.
  93441. * @param vrTeleportationOptions options to modify teleportation behavior.
  93442. */
  93443. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93444. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93445. if (!this._teleportationInitialized) {
  93446. this._teleportationRequested = true;
  93447. this.enableInteractions();
  93448. if (vrTeleportationOptions.floorMeshName) {
  93449. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93450. }
  93451. if (vrTeleportationOptions.floorMeshes) {
  93452. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93453. }
  93454. if (this.leftController != null) {
  93455. this._enableTeleportationOnController(this.leftController);
  93456. }
  93457. if (this.rightController != null) {
  93458. this._enableTeleportationOnController(this.rightController);
  93459. }
  93460. // Creates an image processing post process for the vignette not relying
  93461. // on the main scene configuration for image processing to reduce setup and spaces
  93462. // (gamma/linear) conflicts.
  93463. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93464. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93465. imageProcessingConfiguration.vignetteEnabled = true;
  93466. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93467. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93468. this._teleportationInitialized = true;
  93469. if (this._isDefaultTeleportationTarget) {
  93470. this._createTeleportationCircles();
  93471. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93472. }
  93473. }
  93474. };
  93475. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93476. var _this = this;
  93477. var controllerMesh = controller.webVRController.mesh;
  93478. if (controllerMesh) {
  93479. controller._interactionsEnabled = true;
  93480. controller._activatePointer();
  93481. if (this.webVROptions.laserToggle) {
  93482. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93483. // Enabling / disabling laserPointer
  93484. if (_this._displayLaserPointer && stateObject.value === 1) {
  93485. if (controller._activePointer) {
  93486. controller._deactivatePointer();
  93487. }
  93488. else {
  93489. controller._activatePointer();
  93490. }
  93491. if (_this.displayGaze) {
  93492. controller._gazeTracker.isVisible = controller._activePointer;
  93493. }
  93494. }
  93495. });
  93496. }
  93497. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93498. var gazer = controller;
  93499. if (_this._noControllerIsActive) {
  93500. gazer = _this._cameraGazer;
  93501. }
  93502. if (!gazer._pointerDownOnMeshAsked) {
  93503. if (stateObject.value > _this._padSensibilityUp) {
  93504. gazer._selectionPointerDown();
  93505. }
  93506. }
  93507. else if (stateObject.value < _this._padSensibilityDown) {
  93508. gazer._selectionPointerUp();
  93509. }
  93510. });
  93511. }
  93512. };
  93513. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93514. // Dont teleport if another gaze already requested teleportation
  93515. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93516. return;
  93517. }
  93518. if (!gazer._teleportationRequestInitiated) {
  93519. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93520. gazer._activatePointer();
  93521. gazer._teleportationRequestInitiated = true;
  93522. }
  93523. }
  93524. else {
  93525. // Listening to the proper controller values changes to confirm teleportation
  93526. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93527. if (this._teleportActive) {
  93528. this._teleportCamera(this._haloCenter);
  93529. }
  93530. gazer._teleportationRequestInitiated = false;
  93531. }
  93532. }
  93533. };
  93534. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93535. // Only rotate when user is not currently selecting a teleportation location
  93536. if (gazer._teleportationRequestInitiated) {
  93537. return;
  93538. }
  93539. if (!gazer._rotationLeftAsked) {
  93540. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93541. gazer._rotationLeftAsked = true;
  93542. if (this._rotationAllowed) {
  93543. this._rotateCamera(false);
  93544. }
  93545. }
  93546. }
  93547. else {
  93548. if (stateObject.x > -this._padSensibilityDown) {
  93549. gazer._rotationLeftAsked = false;
  93550. }
  93551. }
  93552. if (!gazer._rotationRightAsked) {
  93553. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93554. gazer._rotationRightAsked = true;
  93555. if (this._rotationAllowed) {
  93556. this._rotateCamera(true);
  93557. }
  93558. }
  93559. }
  93560. else {
  93561. if (stateObject.x < this._padSensibilityDown) {
  93562. gazer._rotationRightAsked = false;
  93563. }
  93564. }
  93565. };
  93566. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93567. // Only teleport backwards when user is not currently selecting a teleportation location
  93568. if (gazer._teleportationRequestInitiated) {
  93569. return;
  93570. }
  93571. // Teleport backwards
  93572. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93573. if (!gazer._teleportationBackRequestInitiated) {
  93574. if (!this.currentVRCamera) {
  93575. return;
  93576. }
  93577. // Get rotation and position of the current camera
  93578. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93579. var position = this.currentVRCamera.position;
  93580. // If the camera has device position, use that instead
  93581. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93582. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93583. position = this.currentVRCamera.devicePosition;
  93584. }
  93585. // Get matrix with only the y rotation of the device rotation
  93586. rotation.toEulerAnglesToRef(this._workingVector);
  93587. this._workingVector.z = 0;
  93588. this._workingVector.x = 0;
  93589. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93590. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93591. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93592. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93593. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93594. var ray = new BABYLON.Ray(position, this._workingVector);
  93595. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93596. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93597. this._teleportCamera(hit.pickedPoint);
  93598. }
  93599. gazer._teleportationBackRequestInitiated = true;
  93600. }
  93601. }
  93602. else {
  93603. gazer._teleportationBackRequestInitiated = false;
  93604. }
  93605. };
  93606. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93607. var _this = this;
  93608. var controllerMesh = controller.webVRController.mesh;
  93609. if (controllerMesh) {
  93610. if (!controller._interactionsEnabled) {
  93611. this._enableInteractionOnController(controller);
  93612. }
  93613. controller._interactionsEnabled = true;
  93614. controller._teleportationEnabled = true;
  93615. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93616. controller._dpadPressed = false;
  93617. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93618. controller._dpadPressed = stateObject.pressed;
  93619. if (!controller._dpadPressed) {
  93620. controller._rotationLeftAsked = false;
  93621. controller._rotationRightAsked = false;
  93622. controller._teleportationBackRequestInitiated = false;
  93623. }
  93624. });
  93625. }
  93626. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93627. if (_this.teleportationEnabled) {
  93628. _this._checkTeleportBackwards(stateObject, controller);
  93629. _this._checkTeleportWithRay(stateObject, controller);
  93630. }
  93631. _this._checkRotate(stateObject, controller);
  93632. });
  93633. }
  93634. };
  93635. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93636. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93637. this._teleportationTarget.isPickable = false;
  93638. var length = 512;
  93639. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93640. dynamicTexture.hasAlpha = true;
  93641. var context = dynamicTexture.getContext();
  93642. var centerX = length / 2;
  93643. var centerY = length / 2;
  93644. var radius = 200;
  93645. context.beginPath();
  93646. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93647. context.fillStyle = this._teleportationFillColor;
  93648. context.fill();
  93649. context.lineWidth = 10;
  93650. context.strokeStyle = this._teleportationBorderColor;
  93651. context.stroke();
  93652. context.closePath();
  93653. dynamicTexture.update();
  93654. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93655. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93656. this._teleportationTarget.material = teleportationCircleMaterial;
  93657. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93658. torus.isPickable = false;
  93659. torus.parent = this._teleportationTarget;
  93660. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93661. var keys = [];
  93662. keys.push({
  93663. frame: 0,
  93664. value: 0
  93665. });
  93666. keys.push({
  93667. frame: 30,
  93668. value: 0.4
  93669. });
  93670. keys.push({
  93671. frame: 60,
  93672. value: 0
  93673. });
  93674. animationInnerCircle.setKeys(keys);
  93675. var easingFunction = new BABYLON.SineEase();
  93676. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93677. animationInnerCircle.setEasingFunction(easingFunction);
  93678. torus.animations = [];
  93679. torus.animations.push(animationInnerCircle);
  93680. this._scene.beginAnimation(torus, 0, 60, true);
  93681. this._hideTeleportationTarget();
  93682. };
  93683. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93684. this._teleportActive = true;
  93685. if (this._teleportationInitialized) {
  93686. this._teleportationTarget.isVisible = true;
  93687. if (this._isDefaultTeleportationTarget) {
  93688. this._teleportationTarget.getChildren()[0].isVisible = true;
  93689. }
  93690. }
  93691. };
  93692. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93693. this._teleportActive = false;
  93694. if (this._teleportationInitialized) {
  93695. this._teleportationTarget.isVisible = false;
  93696. if (this._isDefaultTeleportationTarget) {
  93697. this._teleportationTarget.getChildren()[0].isVisible = false;
  93698. }
  93699. }
  93700. };
  93701. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93702. var _this = this;
  93703. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93704. return;
  93705. }
  93706. if (right) {
  93707. this._rotationAngle++;
  93708. }
  93709. else {
  93710. this._rotationAngle--;
  93711. }
  93712. this.currentVRCamera.animations = [];
  93713. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93714. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93715. var animationRotationKeys = [];
  93716. animationRotationKeys.push({
  93717. frame: 0,
  93718. value: this.currentVRCamera.rotationQuaternion
  93719. });
  93720. animationRotationKeys.push({
  93721. frame: 6,
  93722. value: target
  93723. });
  93724. animationRotation.setKeys(animationRotationKeys);
  93725. animationRotation.setEasingFunction(this._circleEase);
  93726. this.currentVRCamera.animations.push(animationRotation);
  93727. this._postProcessMove.animations = [];
  93728. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93729. var vignetteWeightKeys = [];
  93730. vignetteWeightKeys.push({
  93731. frame: 0,
  93732. value: 0
  93733. });
  93734. vignetteWeightKeys.push({
  93735. frame: 3,
  93736. value: 4
  93737. });
  93738. vignetteWeightKeys.push({
  93739. frame: 6,
  93740. value: 0
  93741. });
  93742. animationPP.setKeys(vignetteWeightKeys);
  93743. animationPP.setEasingFunction(this._circleEase);
  93744. this._postProcessMove.animations.push(animationPP);
  93745. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93746. var vignetteStretchKeys = [];
  93747. vignetteStretchKeys.push({
  93748. frame: 0,
  93749. value: 0
  93750. });
  93751. vignetteStretchKeys.push({
  93752. frame: 3,
  93753. value: 10
  93754. });
  93755. vignetteStretchKeys.push({
  93756. frame: 6,
  93757. value: 0
  93758. });
  93759. animationPP2.setKeys(vignetteStretchKeys);
  93760. animationPP2.setEasingFunction(this._circleEase);
  93761. this._postProcessMove.animations.push(animationPP2);
  93762. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93763. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93764. this._postProcessMove.samples = 4;
  93765. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93766. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93767. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93768. });
  93769. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93770. };
  93771. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93772. if (hit.pickedPoint) {
  93773. if (gazer._teleportationRequestInitiated) {
  93774. this._displayTeleportationTarget();
  93775. this._haloCenter.copyFrom(hit.pickedPoint);
  93776. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93777. }
  93778. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93779. if (pickNormal) {
  93780. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93781. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93782. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93783. }
  93784. this._teleportationTarget.position.y += 0.1;
  93785. }
  93786. };
  93787. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93788. var _this = this;
  93789. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93790. return;
  93791. }
  93792. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93793. // offset of the headset from the anchor.
  93794. if (this.webVRCamera.leftCamera) {
  93795. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93796. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93797. location.subtractToRef(this._workingVector, this._workingVector);
  93798. }
  93799. else {
  93800. this._workingVector.copyFrom(location);
  93801. }
  93802. // Add height to account for user's height offset
  93803. if (this.isInVRMode) {
  93804. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93805. }
  93806. else {
  93807. this._workingVector.y += this._defaultHeight;
  93808. }
  93809. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93810. // Create animation from the camera's position to the new location
  93811. this.currentVRCamera.animations = [];
  93812. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93813. var animationCameraTeleportationKeys = [{
  93814. frame: 0,
  93815. value: this.currentVRCamera.position
  93816. },
  93817. {
  93818. frame: 11,
  93819. value: this._workingVector
  93820. }
  93821. ];
  93822. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93823. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93824. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93825. this._postProcessMove.animations = [];
  93826. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93827. var vignetteWeightKeys = [];
  93828. vignetteWeightKeys.push({
  93829. frame: 0,
  93830. value: 0
  93831. });
  93832. vignetteWeightKeys.push({
  93833. frame: 5,
  93834. value: 8
  93835. });
  93836. vignetteWeightKeys.push({
  93837. frame: 11,
  93838. value: 0
  93839. });
  93840. animationPP.setKeys(vignetteWeightKeys);
  93841. this._postProcessMove.animations.push(animationPP);
  93842. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93843. var vignetteStretchKeys = [];
  93844. vignetteStretchKeys.push({
  93845. frame: 0,
  93846. value: 0
  93847. });
  93848. vignetteStretchKeys.push({
  93849. frame: 5,
  93850. value: 10
  93851. });
  93852. vignetteStretchKeys.push({
  93853. frame: 11,
  93854. value: 0
  93855. });
  93856. animationPP2.setKeys(vignetteStretchKeys);
  93857. this._postProcessMove.animations.push(animationPP2);
  93858. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93859. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93860. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93861. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93862. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93863. });
  93864. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93865. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93866. });
  93867. this._hideTeleportationTarget();
  93868. };
  93869. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93870. if (normal) {
  93871. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93872. if (angle < Math.PI / 2) {
  93873. normal.scaleInPlace(-1);
  93874. }
  93875. }
  93876. return normal;
  93877. };
  93878. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93879. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93880. return;
  93881. }
  93882. var ray = gazer._getForwardRay(this._rayLength);
  93883. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93884. if (hit) {
  93885. // Populate the contrllers mesh that can be used for drag/drop
  93886. if (gazer._laserPointer) {
  93887. hit.originMesh = gazer._laserPointer.parent;
  93888. }
  93889. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93890. }
  93891. gazer._currentHit = hit;
  93892. // Moving the gazeTracker on the mesh face targetted
  93893. if (hit && hit.pickedPoint) {
  93894. if (this._displayGaze) {
  93895. var multiplier = 1;
  93896. gazer._gazeTracker.isVisible = true;
  93897. if (gazer._isActionableMesh) {
  93898. multiplier = 3;
  93899. }
  93900. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93901. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93902. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93903. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93904. // To avoid z-fighting
  93905. var deltaFighting = 0.002;
  93906. if (pickNormal) {
  93907. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93908. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93909. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93910. }
  93911. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93912. if (gazer._gazeTracker.position.x < 0) {
  93913. gazer._gazeTracker.position.x += deltaFighting;
  93914. }
  93915. else {
  93916. gazer._gazeTracker.position.x -= deltaFighting;
  93917. }
  93918. if (gazer._gazeTracker.position.y < 0) {
  93919. gazer._gazeTracker.position.y += deltaFighting;
  93920. }
  93921. else {
  93922. gazer._gazeTracker.position.y -= deltaFighting;
  93923. }
  93924. if (gazer._gazeTracker.position.z < 0) {
  93925. gazer._gazeTracker.position.z += deltaFighting;
  93926. }
  93927. else {
  93928. gazer._gazeTracker.position.z -= deltaFighting;
  93929. }
  93930. }
  93931. // Changing the size of the laser pointer based on the distance from the targetted point
  93932. gazer._updatePointerDistance(hit.distance);
  93933. }
  93934. else {
  93935. gazer._updatePointerDistance();
  93936. gazer._gazeTracker.isVisible = false;
  93937. }
  93938. if (hit && hit.pickedMesh) {
  93939. // The object selected is the floor, we're in a teleportation scenario
  93940. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93941. // Moving the teleportation area to this targetted point
  93942. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93943. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93944. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93945. }
  93946. gazer._currentMeshSelected = null;
  93947. if (gazer._teleportationRequestInitiated) {
  93948. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93949. }
  93950. return;
  93951. }
  93952. // If not, we're in a selection scenario
  93953. //this._teleportationAllowed = false;
  93954. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93955. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93956. this.onNewMeshPicked.notifyObservers(hit);
  93957. gazer._currentMeshSelected = hit.pickedMesh;
  93958. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93959. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93960. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93961. gazer._isActionableMesh = true;
  93962. }
  93963. else {
  93964. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93965. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93966. gazer._isActionableMesh = false;
  93967. }
  93968. try {
  93969. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93970. }
  93971. catch (err) {
  93972. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93973. }
  93974. }
  93975. else {
  93976. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93977. gazer._currentMeshSelected = null;
  93978. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93979. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93980. }
  93981. }
  93982. }
  93983. else {
  93984. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93985. gazer._currentMeshSelected = null;
  93986. //this._teleportationAllowed = false;
  93987. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93988. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93989. }
  93990. };
  93991. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93992. if (mesh) {
  93993. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93994. }
  93995. };
  93996. /**
  93997. * Sets the color of the laser ray from the vr controllers.
  93998. * @param color new color for the ray.
  93999. */
  94000. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94001. if (this.leftController) {
  94002. this.leftController._setLaserPointerColor(color);
  94003. }
  94004. if (this.rightController) {
  94005. this.rightController._setLaserPointerColor(color);
  94006. }
  94007. };
  94008. /**
  94009. * Sets the color of the ray from the vr headsets gaze.
  94010. * @param color new color for the ray.
  94011. */
  94012. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94013. if (!this._cameraGazer._gazeTracker.material) {
  94014. return;
  94015. }
  94016. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94017. if (this.leftController) {
  94018. this.leftController._gazeTracker.material.emissiveColor = color;
  94019. }
  94020. if (this.rightController) {
  94021. this.rightController._gazeTracker.material.emissiveColor = color;
  94022. }
  94023. };
  94024. /**
  94025. * Exits VR and disposes of the vr experience helper
  94026. */
  94027. VRExperienceHelper.prototype.dispose = function () {
  94028. if (this.isInVRMode) {
  94029. this.exitVR();
  94030. }
  94031. if (this._postProcessMove) {
  94032. this._postProcessMove.dispose();
  94033. }
  94034. if (this._webVRCamera) {
  94035. this._webVRCamera.dispose();
  94036. }
  94037. if (this._vrDeviceOrientationCamera) {
  94038. this._vrDeviceOrientationCamera.dispose();
  94039. }
  94040. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94041. document.body.removeChild(this._btnVR);
  94042. }
  94043. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94044. this._deviceOrientationCamera.dispose();
  94045. }
  94046. if (this._cameraGazer) {
  94047. this._cameraGazer.dispose();
  94048. }
  94049. if (this.leftController) {
  94050. this.leftController.dispose();
  94051. }
  94052. if (this.rightController) {
  94053. this.rightController.dispose();
  94054. }
  94055. if (this._teleportationTarget) {
  94056. this._teleportationTarget.dispose();
  94057. }
  94058. this._floorMeshesCollection = [];
  94059. document.removeEventListener("keydown", this._onKeyDown);
  94060. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94061. window.removeEventListener("resize", this._onResize);
  94062. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94063. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94064. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94065. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94066. document.onmsfullscreenchange = null;
  94067. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94068. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94069. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94070. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94071. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94072. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94073. this._scene.unregisterBeforeRender(this.beforeRender);
  94074. };
  94075. /**
  94076. * Gets the name of the VRExperienceHelper class
  94077. * @returns "VRExperienceHelper"
  94078. */
  94079. VRExperienceHelper.prototype.getClassName = function () {
  94080. return "VRExperienceHelper";
  94081. };
  94082. return VRExperienceHelper;
  94083. }());
  94084. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94085. })(BABYLON || (BABYLON = {}));
  94086. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94087. // Mainly based on these 2 articles :
  94088. // 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
  94089. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94090. var BABYLON;
  94091. (function (BABYLON) {
  94092. /**
  94093. * Defines the potential axis of a Joystick
  94094. */
  94095. var JoystickAxis;
  94096. (function (JoystickAxis) {
  94097. /** X axis */
  94098. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94099. /** Y axis */
  94100. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94101. /** Z axis */
  94102. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94103. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94104. /**
  94105. * Class used to define virtual joystick (used in touch mode)
  94106. */
  94107. var VirtualJoystick = /** @class */ (function () {
  94108. /**
  94109. * Creates a new virtual joystick
  94110. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94111. */
  94112. function VirtualJoystick(leftJoystick) {
  94113. var _this = this;
  94114. if (leftJoystick) {
  94115. this._leftJoystick = true;
  94116. }
  94117. else {
  94118. this._leftJoystick = false;
  94119. }
  94120. VirtualJoystick._globalJoystickIndex++;
  94121. // By default left & right arrow keys are moving the X
  94122. // and up & down keys are moving the Y
  94123. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94124. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94125. this.reverseLeftRight = false;
  94126. this.reverseUpDown = false;
  94127. // collections of pointers
  94128. this._touches = new BABYLON.StringDictionary();
  94129. this.deltaPosition = BABYLON.Vector3.Zero();
  94130. this._joystickSensibility = 25;
  94131. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94132. this._onResize = function (evt) {
  94133. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94134. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94135. if (VirtualJoystick.vjCanvas) {
  94136. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94137. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94138. }
  94139. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94140. };
  94141. // injecting a canvas element on top of the canvas 3D game
  94142. if (!VirtualJoystick.vjCanvas) {
  94143. window.addEventListener("resize", this._onResize, false);
  94144. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94145. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94146. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94147. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94148. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94149. VirtualJoystick.vjCanvas.style.width = "100%";
  94150. VirtualJoystick.vjCanvas.style.height = "100%";
  94151. VirtualJoystick.vjCanvas.style.position = "absolute";
  94152. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94153. VirtualJoystick.vjCanvas.style.top = "0px";
  94154. VirtualJoystick.vjCanvas.style.left = "0px";
  94155. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94156. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94157. // Support for jQuery PEP polyfill
  94158. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94159. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94160. if (!context) {
  94161. throw new Error("Unable to create canvas for virtual joystick");
  94162. }
  94163. VirtualJoystick.vjCanvasContext = context;
  94164. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94165. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94166. document.body.appendChild(VirtualJoystick.vjCanvas);
  94167. }
  94168. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94169. this.pressed = false;
  94170. // default joystick color
  94171. this._joystickColor = "cyan";
  94172. this._joystickPointerID = -1;
  94173. // current joystick position
  94174. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94175. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94176. // origin joystick position
  94177. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94178. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94179. this._onPointerDownHandlerRef = function (evt) {
  94180. _this._onPointerDown(evt);
  94181. };
  94182. this._onPointerMoveHandlerRef = function (evt) {
  94183. _this._onPointerMove(evt);
  94184. };
  94185. this._onPointerUpHandlerRef = function (evt) {
  94186. _this._onPointerUp(evt);
  94187. };
  94188. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94189. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94190. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94191. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94192. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94193. evt.preventDefault(); // Disables system menu
  94194. }, false);
  94195. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94196. }
  94197. /**
  94198. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94199. * @param newJoystickSensibility defines the new sensibility
  94200. */
  94201. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94202. this._joystickSensibility = newJoystickSensibility;
  94203. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94204. };
  94205. VirtualJoystick.prototype._onPointerDown = function (e) {
  94206. var positionOnScreenCondition;
  94207. e.preventDefault();
  94208. if (this._leftJoystick === true) {
  94209. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94210. }
  94211. else {
  94212. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94213. }
  94214. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94215. // First contact will be dedicated to the virtual joystick
  94216. this._joystickPointerID = e.pointerId;
  94217. this._joystickPointerStartPos.x = e.clientX;
  94218. this._joystickPointerStartPos.y = e.clientY;
  94219. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94220. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94221. this._deltaJoystickVector.x = 0;
  94222. this._deltaJoystickVector.y = 0;
  94223. this.pressed = true;
  94224. this._touches.add(e.pointerId.toString(), e);
  94225. }
  94226. else {
  94227. // You can only trigger the action buttons with a joystick declared
  94228. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94229. this._action();
  94230. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94231. }
  94232. }
  94233. };
  94234. VirtualJoystick.prototype._onPointerMove = function (e) {
  94235. // If the current pointer is the one associated to the joystick (first touch contact)
  94236. if (this._joystickPointerID == e.pointerId) {
  94237. this._joystickPointerPos.x = e.clientX;
  94238. this._joystickPointerPos.y = e.clientY;
  94239. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94240. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94241. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94242. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94243. switch (this._axisTargetedByLeftAndRight) {
  94244. case JoystickAxis.X:
  94245. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94246. break;
  94247. case JoystickAxis.Y:
  94248. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94249. break;
  94250. case JoystickAxis.Z:
  94251. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94252. break;
  94253. }
  94254. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94255. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94256. switch (this._axisTargetedByUpAndDown) {
  94257. case JoystickAxis.X:
  94258. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94259. break;
  94260. case JoystickAxis.Y:
  94261. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94262. break;
  94263. case JoystickAxis.Z:
  94264. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94265. break;
  94266. }
  94267. }
  94268. else {
  94269. var data = this._touches.get(e.pointerId.toString());
  94270. if (data) {
  94271. data.x = e.clientX;
  94272. data.y = e.clientY;
  94273. }
  94274. }
  94275. };
  94276. VirtualJoystick.prototype._onPointerUp = function (e) {
  94277. if (this._joystickPointerID == e.pointerId) {
  94278. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94279. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94280. this._joystickPointerID = -1;
  94281. this.pressed = false;
  94282. }
  94283. else {
  94284. var touch = this._touches.get(e.pointerId.toString());
  94285. if (touch) {
  94286. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94287. }
  94288. }
  94289. this._deltaJoystickVector.x = 0;
  94290. this._deltaJoystickVector.y = 0;
  94291. this._touches.remove(e.pointerId.toString());
  94292. };
  94293. /**
  94294. * Change the color of the virtual joystick
  94295. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94296. */
  94297. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94298. this._joystickColor = newColor;
  94299. };
  94300. /**
  94301. * Defines a callback to call when the joystick is touched
  94302. * @param action defines the callback
  94303. */
  94304. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94305. this._action = action;
  94306. };
  94307. /**
  94308. * Defines which axis you'd like to control for left & right
  94309. * @param axis defines the axis to use
  94310. */
  94311. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94312. switch (axis) {
  94313. case JoystickAxis.X:
  94314. case JoystickAxis.Y:
  94315. case JoystickAxis.Z:
  94316. this._axisTargetedByLeftAndRight = axis;
  94317. break;
  94318. default:
  94319. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94320. break;
  94321. }
  94322. };
  94323. /**
  94324. * Defines which axis you'd like to control for up & down
  94325. * @param axis defines the axis to use
  94326. */
  94327. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94328. switch (axis) {
  94329. case JoystickAxis.X:
  94330. case JoystickAxis.Y:
  94331. case JoystickAxis.Z:
  94332. this._axisTargetedByUpAndDown = axis;
  94333. break;
  94334. default:
  94335. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94336. break;
  94337. }
  94338. };
  94339. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94340. var _this = this;
  94341. if (this.pressed) {
  94342. this._touches.forEach(function (key, touch) {
  94343. if (touch.pointerId === _this._joystickPointerID) {
  94344. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94345. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94346. VirtualJoystick.vjCanvasContext.beginPath();
  94347. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94348. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94349. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94350. VirtualJoystick.vjCanvasContext.stroke();
  94351. VirtualJoystick.vjCanvasContext.closePath();
  94352. VirtualJoystick.vjCanvasContext.beginPath();
  94353. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94354. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94355. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94356. VirtualJoystick.vjCanvasContext.stroke();
  94357. VirtualJoystick.vjCanvasContext.closePath();
  94358. VirtualJoystick.vjCanvasContext.beginPath();
  94359. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94360. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94361. VirtualJoystick.vjCanvasContext.stroke();
  94362. VirtualJoystick.vjCanvasContext.closePath();
  94363. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94364. }
  94365. else {
  94366. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94367. VirtualJoystick.vjCanvasContext.beginPath();
  94368. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94369. VirtualJoystick.vjCanvasContext.beginPath();
  94370. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94371. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94372. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94373. VirtualJoystick.vjCanvasContext.stroke();
  94374. VirtualJoystick.vjCanvasContext.closePath();
  94375. touch.prevX = touch.x;
  94376. touch.prevY = touch.y;
  94377. }
  94378. ;
  94379. });
  94380. }
  94381. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94382. };
  94383. /**
  94384. * Release internal HTML canvas
  94385. */
  94386. VirtualJoystick.prototype.releaseCanvas = function () {
  94387. if (VirtualJoystick.vjCanvas) {
  94388. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94389. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94390. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94391. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94392. window.removeEventListener("resize", this._onResize);
  94393. document.body.removeChild(VirtualJoystick.vjCanvas);
  94394. VirtualJoystick.vjCanvas = null;
  94395. }
  94396. };
  94397. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94398. VirtualJoystick._globalJoystickIndex = 0;
  94399. return VirtualJoystick;
  94400. }());
  94401. BABYLON.VirtualJoystick = VirtualJoystick;
  94402. })(BABYLON || (BABYLON = {}));
  94403. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94404. var BABYLON;
  94405. (function (BABYLON) {
  94406. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  94407. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  94408. });
  94409. // We're mainly based on the logic defined into the FreeCamera code
  94410. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94411. __extends(VirtualJoysticksCamera, _super);
  94412. function VirtualJoysticksCamera(name, position, scene) {
  94413. var _this = _super.call(this, name, position, scene) || this;
  94414. _this.inputs.addVirtualJoystick();
  94415. return _this;
  94416. }
  94417. VirtualJoysticksCamera.prototype.getClassName = function () {
  94418. return "VirtualJoysticksCamera";
  94419. };
  94420. return VirtualJoysticksCamera;
  94421. }(BABYLON.FreeCamera));
  94422. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94423. })(BABYLON || (BABYLON = {}));
  94424. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94425. var BABYLON;
  94426. (function (BABYLON) {
  94427. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94428. function FreeCameraVirtualJoystickInput() {
  94429. }
  94430. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94431. return this._leftjoystick;
  94432. };
  94433. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94434. return this._rightjoystick;
  94435. };
  94436. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94437. if (this._leftjoystick) {
  94438. var camera = this.camera;
  94439. var speed = camera._computeLocalCameraSpeed() * 50;
  94440. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94441. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94442. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94443. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94444. if (!this._leftjoystick.pressed) {
  94445. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94446. }
  94447. if (!this._rightjoystick.pressed) {
  94448. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94449. }
  94450. }
  94451. };
  94452. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94453. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94454. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94455. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94456. this._leftjoystick.setJoystickSensibility(0.15);
  94457. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94458. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94459. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94460. this._rightjoystick.reverseUpDown = true;
  94461. this._rightjoystick.setJoystickSensibility(0.05);
  94462. this._rightjoystick.setJoystickColor("yellow");
  94463. };
  94464. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94465. this._leftjoystick.releaseCanvas();
  94466. this._rightjoystick.releaseCanvas();
  94467. };
  94468. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94469. return "FreeCameraVirtualJoystickInput";
  94470. };
  94471. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94472. return "virtualJoystick";
  94473. };
  94474. return FreeCameraVirtualJoystickInput;
  94475. }());
  94476. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94477. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94478. })(BABYLON || (BABYLON = {}));
  94479. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94480. var BABYLON;
  94481. (function (BABYLON) {
  94482. var SimplificationSettings = /** @class */ (function () {
  94483. function SimplificationSettings(quality, distance, optimizeMesh) {
  94484. this.quality = quality;
  94485. this.distance = distance;
  94486. this.optimizeMesh = optimizeMesh;
  94487. }
  94488. return SimplificationSettings;
  94489. }());
  94490. BABYLON.SimplificationSettings = SimplificationSettings;
  94491. var SimplificationQueue = /** @class */ (function () {
  94492. function SimplificationQueue() {
  94493. this.running = false;
  94494. this._simplificationArray = [];
  94495. }
  94496. SimplificationQueue.prototype.addTask = function (task) {
  94497. this._simplificationArray.push(task);
  94498. };
  94499. SimplificationQueue.prototype.executeNext = function () {
  94500. var task = this._simplificationArray.pop();
  94501. if (task) {
  94502. this.running = true;
  94503. this.runSimplification(task);
  94504. }
  94505. else {
  94506. this.running = false;
  94507. }
  94508. };
  94509. SimplificationQueue.prototype.runSimplification = function (task) {
  94510. var _this = this;
  94511. if (task.parallelProcessing) {
  94512. //parallel simplifier
  94513. task.settings.forEach(function (setting) {
  94514. var simplifier = _this.getSimplifier(task);
  94515. simplifier.simplify(setting, function (newMesh) {
  94516. task.mesh.addLODLevel(setting.distance, newMesh);
  94517. newMesh.isVisible = true;
  94518. //check if it is the last
  94519. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94520. //all done, run the success callback.
  94521. task.successCallback();
  94522. }
  94523. _this.executeNext();
  94524. });
  94525. });
  94526. }
  94527. else {
  94528. //single simplifier.
  94529. var simplifier = this.getSimplifier(task);
  94530. var runDecimation = function (setting, callback) {
  94531. simplifier.simplify(setting, function (newMesh) {
  94532. task.mesh.addLODLevel(setting.distance, newMesh);
  94533. newMesh.isVisible = true;
  94534. //run the next quality level
  94535. callback();
  94536. });
  94537. };
  94538. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94539. runDecimation(task.settings[loop.index], function () {
  94540. loop.executeNext();
  94541. });
  94542. }, function () {
  94543. //execution ended, run the success callback.
  94544. if (task.successCallback) {
  94545. task.successCallback();
  94546. }
  94547. _this.executeNext();
  94548. });
  94549. }
  94550. };
  94551. SimplificationQueue.prototype.getSimplifier = function (task) {
  94552. switch (task.simplificationType) {
  94553. case SimplificationType.QUADRATIC:
  94554. default:
  94555. return new QuadraticErrorSimplification(task.mesh);
  94556. }
  94557. };
  94558. return SimplificationQueue;
  94559. }());
  94560. BABYLON.SimplificationQueue = SimplificationQueue;
  94561. /**
  94562. * The implemented types of simplification
  94563. * At the moment only Quadratic Error Decimation is implemented
  94564. */
  94565. var SimplificationType;
  94566. (function (SimplificationType) {
  94567. /** Quadratic error decimation */
  94568. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94569. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94570. var DecimationTriangle = /** @class */ (function () {
  94571. function DecimationTriangle(vertices) {
  94572. this.vertices = vertices;
  94573. this.error = new Array(4);
  94574. this.deleted = false;
  94575. this.isDirty = false;
  94576. this.deletePending = false;
  94577. this.borderFactor = 0;
  94578. }
  94579. return DecimationTriangle;
  94580. }());
  94581. BABYLON.DecimationTriangle = DecimationTriangle;
  94582. var DecimationVertex = /** @class */ (function () {
  94583. function DecimationVertex(position, id) {
  94584. this.position = position;
  94585. this.id = id;
  94586. this.isBorder = true;
  94587. this.q = new QuadraticMatrix();
  94588. this.triangleCount = 0;
  94589. this.triangleStart = 0;
  94590. this.originalOffsets = [];
  94591. }
  94592. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94593. this.position.copyFrom(newPosition);
  94594. };
  94595. return DecimationVertex;
  94596. }());
  94597. BABYLON.DecimationVertex = DecimationVertex;
  94598. var QuadraticMatrix = /** @class */ (function () {
  94599. function QuadraticMatrix(data) {
  94600. this.data = new Array(10);
  94601. for (var i = 0; i < 10; ++i) {
  94602. if (data && data[i]) {
  94603. this.data[i] = data[i];
  94604. }
  94605. else {
  94606. this.data[i] = 0;
  94607. }
  94608. }
  94609. }
  94610. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94611. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94612. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94613. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94614. return det;
  94615. };
  94616. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94617. for (var i = 0; i < 10; ++i) {
  94618. this.data[i] += matrix.data[i];
  94619. }
  94620. };
  94621. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94622. for (var i = 0; i < 10; ++i) {
  94623. this.data[i] += data[i];
  94624. }
  94625. };
  94626. QuadraticMatrix.prototype.add = function (matrix) {
  94627. var m = new QuadraticMatrix();
  94628. for (var i = 0; i < 10; ++i) {
  94629. m.data[i] = this.data[i] + matrix.data[i];
  94630. }
  94631. return m;
  94632. };
  94633. QuadraticMatrix.FromData = function (a, b, c, d) {
  94634. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94635. };
  94636. //returning an array to avoid garbage collection
  94637. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94638. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94639. };
  94640. return QuadraticMatrix;
  94641. }());
  94642. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94643. var Reference = /** @class */ (function () {
  94644. function Reference(vertexId, triangleId) {
  94645. this.vertexId = vertexId;
  94646. this.triangleId = triangleId;
  94647. }
  94648. return Reference;
  94649. }());
  94650. BABYLON.Reference = Reference;
  94651. /**
  94652. * An implementation of the Quadratic Error simplification algorithm.
  94653. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94654. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94655. * @author RaananW
  94656. */
  94657. var QuadraticErrorSimplification = /** @class */ (function () {
  94658. function QuadraticErrorSimplification(_mesh) {
  94659. this._mesh = _mesh;
  94660. this.syncIterations = 5000;
  94661. this.aggressiveness = 7;
  94662. this.decimationIterations = 100;
  94663. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94664. }
  94665. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94666. var _this = this;
  94667. this.initDecimatedMesh();
  94668. //iterating through the submeshes array, one after the other.
  94669. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94670. _this.initWithMesh(loop.index, function () {
  94671. _this.runDecimation(settings, loop.index, function () {
  94672. loop.executeNext();
  94673. });
  94674. }, settings.optimizeMesh);
  94675. }, function () {
  94676. setTimeout(function () {
  94677. successCallback(_this._reconstructedMesh);
  94678. }, 0);
  94679. });
  94680. };
  94681. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94682. var _this = this;
  94683. var targetCount = ~~(this.triangles.length * settings.quality);
  94684. var deletedTriangles = 0;
  94685. var triangleCount = this.triangles.length;
  94686. var iterationFunction = function (iteration, callback) {
  94687. setTimeout(function () {
  94688. if (iteration % 5 === 0) {
  94689. _this.updateMesh(iteration === 0);
  94690. }
  94691. for (var i = 0; i < _this.triangles.length; ++i) {
  94692. _this.triangles[i].isDirty = false;
  94693. }
  94694. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94695. var trianglesIterator = function (i) {
  94696. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94697. var t = _this.triangles[tIdx];
  94698. if (!t)
  94699. return;
  94700. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94701. return;
  94702. }
  94703. for (var j = 0; j < 3; ++j) {
  94704. if (t.error[j] < threshold) {
  94705. var deleted0 = [];
  94706. var deleted1 = [];
  94707. var v0 = t.vertices[j];
  94708. var v1 = t.vertices[(j + 1) % 3];
  94709. if (v0.isBorder || v1.isBorder)
  94710. continue;
  94711. var p = BABYLON.Vector3.Zero();
  94712. var n = BABYLON.Vector3.Zero();
  94713. var uv = BABYLON.Vector2.Zero();
  94714. var color = new BABYLON.Color4(0, 0, 0, 1);
  94715. _this.calculateError(v0, v1, p, n, uv, color);
  94716. var delTr = new Array();
  94717. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94718. continue;
  94719. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94720. continue;
  94721. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94722. continue;
  94723. var uniqueArray = new Array();
  94724. delTr.forEach(function (deletedT) {
  94725. if (uniqueArray.indexOf(deletedT) === -1) {
  94726. deletedT.deletePending = true;
  94727. uniqueArray.push(deletedT);
  94728. }
  94729. });
  94730. if (uniqueArray.length % 2 !== 0) {
  94731. continue;
  94732. }
  94733. v0.q = v1.q.add(v0.q);
  94734. v0.updatePosition(p);
  94735. var tStart = _this.references.length;
  94736. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94737. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94738. var tCount = _this.references.length - tStart;
  94739. if (tCount <= v0.triangleCount) {
  94740. if (tCount) {
  94741. for (var c = 0; c < tCount; c++) {
  94742. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94743. }
  94744. }
  94745. }
  94746. else {
  94747. v0.triangleStart = tStart;
  94748. }
  94749. v0.triangleCount = tCount;
  94750. break;
  94751. }
  94752. }
  94753. };
  94754. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94755. }, 0);
  94756. };
  94757. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94758. if (triangleCount - deletedTriangles <= targetCount)
  94759. loop.breakLoop();
  94760. else {
  94761. iterationFunction(loop.index, function () {
  94762. loop.executeNext();
  94763. });
  94764. }
  94765. }, function () {
  94766. setTimeout(function () {
  94767. //reconstruct this part of the mesh
  94768. _this.reconstructMesh(submeshIndex);
  94769. successCallback();
  94770. }, 0);
  94771. });
  94772. };
  94773. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94774. var _this = this;
  94775. this.vertices = [];
  94776. this.triangles = [];
  94777. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94778. var indices = this._mesh.getIndices();
  94779. var submesh = this._mesh.subMeshes[submeshIndex];
  94780. var findInVertices = function (positionToSearch) {
  94781. if (optimizeMesh) {
  94782. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94783. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94784. return _this.vertices[ii];
  94785. }
  94786. }
  94787. }
  94788. return null;
  94789. };
  94790. var vertexReferences = [];
  94791. var vertexInit = function (i) {
  94792. if (!positionData) {
  94793. return;
  94794. }
  94795. var offset = i + submesh.verticesStart;
  94796. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94797. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94798. vertex.originalOffsets.push(offset);
  94799. if (vertex.id === _this.vertices.length) {
  94800. _this.vertices.push(vertex);
  94801. }
  94802. vertexReferences.push(vertex.id);
  94803. };
  94804. //var totalVertices = mesh.getTotalVertices();
  94805. var totalVertices = submesh.verticesCount;
  94806. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94807. var indicesInit = function (i) {
  94808. if (!indices) {
  94809. return;
  94810. }
  94811. var offset = (submesh.indexStart / 3) + i;
  94812. var pos = (offset * 3);
  94813. var i0 = indices[pos + 0];
  94814. var i1 = indices[pos + 1];
  94815. var i2 = indices[pos + 2];
  94816. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94817. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94818. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94819. var triangle = new DecimationTriangle([v0, v1, v2]);
  94820. triangle.originalOffset = pos;
  94821. _this.triangles.push(triangle);
  94822. };
  94823. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94824. _this.init(callback);
  94825. });
  94826. });
  94827. };
  94828. QuadraticErrorSimplification.prototype.init = function (callback) {
  94829. var _this = this;
  94830. var triangleInit1 = function (i) {
  94831. var t = _this.triangles[i];
  94832. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94833. for (var j = 0; j < 3; j++) {
  94834. 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))));
  94835. }
  94836. };
  94837. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94838. var triangleInit2 = function (i) {
  94839. var t = _this.triangles[i];
  94840. for (var j = 0; j < 3; ++j) {
  94841. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94842. }
  94843. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94844. };
  94845. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94846. callback();
  94847. });
  94848. });
  94849. };
  94850. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94851. var newTriangles = [];
  94852. var i;
  94853. for (i = 0; i < this.vertices.length; ++i) {
  94854. this.vertices[i].triangleCount = 0;
  94855. }
  94856. var t;
  94857. var j;
  94858. for (i = 0; i < this.triangles.length; ++i) {
  94859. if (!this.triangles[i].deleted) {
  94860. t = this.triangles[i];
  94861. for (j = 0; j < 3; ++j) {
  94862. t.vertices[j].triangleCount = 1;
  94863. }
  94864. newTriangles.push(t);
  94865. }
  94866. }
  94867. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94868. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94869. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94870. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94871. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94872. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94873. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94874. var vertexCount = 0;
  94875. for (i = 0; i < this.vertices.length; ++i) {
  94876. var vertex = this.vertices[i];
  94877. vertex.id = vertexCount;
  94878. if (vertex.triangleCount) {
  94879. vertex.originalOffsets.forEach(function (originalOffset) {
  94880. if (!normalData) {
  94881. return;
  94882. }
  94883. newPositionData.push(vertex.position.x);
  94884. newPositionData.push(vertex.position.y);
  94885. newPositionData.push(vertex.position.z);
  94886. newNormalData.push(normalData[originalOffset * 3]);
  94887. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94888. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94889. if (uvs && uvs.length) {
  94890. newUVsData.push(uvs[(originalOffset * 2)]);
  94891. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94892. }
  94893. else if (colorsData && colorsData.length) {
  94894. newColorsData.push(colorsData[(originalOffset * 4)]);
  94895. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94896. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94897. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94898. }
  94899. ++vertexCount;
  94900. });
  94901. }
  94902. }
  94903. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94904. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94905. var submeshesArray = this._reconstructedMesh.subMeshes;
  94906. this._reconstructedMesh.subMeshes = [];
  94907. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94908. var originalIndices = this._mesh.getIndices();
  94909. for (i = 0; i < newTriangles.length; ++i) {
  94910. t = newTriangles[i]; //now get the new referencing point for each vertex
  94911. [0, 1, 2].forEach(function (idx) {
  94912. var id = originalIndices[t.originalOffset + idx];
  94913. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94914. if (offset < 0)
  94915. offset = 0;
  94916. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94917. });
  94918. }
  94919. //overwriting the old vertex buffers and indices.
  94920. this._reconstructedMesh.setIndices(newIndicesArray);
  94921. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94922. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94923. if (newUVsData.length > 0)
  94924. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94925. if (newColorsData.length > 0)
  94926. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94927. //create submesh
  94928. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94929. if (submeshIndex > 0) {
  94930. this._reconstructedMesh.subMeshes = [];
  94931. submeshesArray.forEach(function (submesh) {
  94932. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94933. });
  94934. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94935. }
  94936. };
  94937. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94938. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94939. this._reconstructedMesh.material = this._mesh.material;
  94940. this._reconstructedMesh.parent = this._mesh.parent;
  94941. this._reconstructedMesh.isVisible = false;
  94942. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94943. };
  94944. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94945. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94946. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94947. if (t.deleted)
  94948. continue;
  94949. var s = this.references[vertex1.triangleStart + i].vertexId;
  94950. var v1 = t.vertices[(s + 1) % 3];
  94951. var v2 = t.vertices[(s + 2) % 3];
  94952. if ((v1 === vertex2 || v2 === vertex2)) {
  94953. deletedArray[i] = true;
  94954. delTr.push(t);
  94955. continue;
  94956. }
  94957. var d1 = v1.position.subtract(point);
  94958. d1 = d1.normalize();
  94959. var d2 = v2.position.subtract(point);
  94960. d2 = d2.normalize();
  94961. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94962. return true;
  94963. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94964. deletedArray[i] = false;
  94965. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94966. return true;
  94967. }
  94968. return false;
  94969. };
  94970. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94971. var newDeleted = deletedTriangles;
  94972. for (var i = 0; i < vertex.triangleCount; ++i) {
  94973. var ref = this.references[vertex.triangleStart + i];
  94974. var t = this.triangles[ref.triangleId];
  94975. if (t.deleted)
  94976. continue;
  94977. if (deletedArray[i] && t.deletePending) {
  94978. t.deleted = true;
  94979. newDeleted++;
  94980. continue;
  94981. }
  94982. t.vertices[ref.vertexId] = origVertex;
  94983. t.isDirty = true;
  94984. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94985. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94986. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94987. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94988. this.references.push(ref);
  94989. }
  94990. return newDeleted;
  94991. };
  94992. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94993. for (var i = 0; i < this.vertices.length; ++i) {
  94994. var vCount = [];
  94995. var vId = [];
  94996. var v = this.vertices[i];
  94997. var j;
  94998. for (j = 0; j < v.triangleCount; ++j) {
  94999. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95000. for (var ii = 0; ii < 3; ii++) {
  95001. var ofs = 0;
  95002. var vv = triangle.vertices[ii];
  95003. while (ofs < vCount.length) {
  95004. if (vId[ofs] === vv.id)
  95005. break;
  95006. ++ofs;
  95007. }
  95008. if (ofs === vCount.length) {
  95009. vCount.push(1);
  95010. vId.push(vv.id);
  95011. }
  95012. else {
  95013. vCount[ofs]++;
  95014. }
  95015. }
  95016. }
  95017. for (j = 0; j < vCount.length; ++j) {
  95018. if (vCount[j] === 1) {
  95019. this.vertices[vId[j]].isBorder = true;
  95020. }
  95021. else {
  95022. this.vertices[vId[j]].isBorder = false;
  95023. }
  95024. }
  95025. }
  95026. };
  95027. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95028. if (identifyBorders === void 0) { identifyBorders = false; }
  95029. var i;
  95030. if (!identifyBorders) {
  95031. var newTrianglesVector = [];
  95032. for (i = 0; i < this.triangles.length; ++i) {
  95033. if (!this.triangles[i].deleted) {
  95034. newTrianglesVector.push(this.triangles[i]);
  95035. }
  95036. }
  95037. this.triangles = newTrianglesVector;
  95038. }
  95039. for (i = 0; i < this.vertices.length; ++i) {
  95040. this.vertices[i].triangleCount = 0;
  95041. this.vertices[i].triangleStart = 0;
  95042. }
  95043. var t;
  95044. var j;
  95045. var v;
  95046. for (i = 0; i < this.triangles.length; ++i) {
  95047. t = this.triangles[i];
  95048. for (j = 0; j < 3; ++j) {
  95049. v = t.vertices[j];
  95050. v.triangleCount++;
  95051. }
  95052. }
  95053. var tStart = 0;
  95054. for (i = 0; i < this.vertices.length; ++i) {
  95055. this.vertices[i].triangleStart = tStart;
  95056. tStart += this.vertices[i].triangleCount;
  95057. this.vertices[i].triangleCount = 0;
  95058. }
  95059. var newReferences = new Array(this.triangles.length * 3);
  95060. for (i = 0; i < this.triangles.length; ++i) {
  95061. t = this.triangles[i];
  95062. for (j = 0; j < 3; ++j) {
  95063. v = t.vertices[j];
  95064. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95065. v.triangleCount++;
  95066. }
  95067. }
  95068. this.references = newReferences;
  95069. if (identifyBorders) {
  95070. this.identifyBorder();
  95071. }
  95072. };
  95073. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95074. var x = point.x;
  95075. var y = point.y;
  95076. var z = point.z;
  95077. 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
  95078. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95079. };
  95080. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95081. var q = vertex1.q.add(vertex2.q);
  95082. var border = vertex1.isBorder && vertex2.isBorder;
  95083. var error = 0;
  95084. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95085. if (qDet !== 0 && !border) {
  95086. if (!pointResult) {
  95087. pointResult = BABYLON.Vector3.Zero();
  95088. }
  95089. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95090. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95091. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95092. error = this.vertexError(q, pointResult);
  95093. }
  95094. else {
  95095. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95096. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95097. var error1 = this.vertexError(q, vertex1.position);
  95098. var error2 = this.vertexError(q, vertex2.position);
  95099. var error3 = this.vertexError(q, p3);
  95100. error = Math.min(error1, error2, error3);
  95101. if (error === error1) {
  95102. if (pointResult) {
  95103. pointResult.copyFrom(vertex1.position);
  95104. }
  95105. }
  95106. else if (error === error2) {
  95107. if (pointResult) {
  95108. pointResult.copyFrom(vertex2.position);
  95109. }
  95110. }
  95111. else {
  95112. if (pointResult) {
  95113. pointResult.copyFrom(p3);
  95114. }
  95115. }
  95116. }
  95117. return error;
  95118. };
  95119. return QuadraticErrorSimplification;
  95120. }());
  95121. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95122. })(BABYLON || (BABYLON = {}));
  95123. //# sourceMappingURL=babylon.meshSimplification.js.map
  95124. var BABYLON;
  95125. (function (BABYLON) {
  95126. var MeshLODLevel = /** @class */ (function () {
  95127. function MeshLODLevel(distance, mesh) {
  95128. this.distance = distance;
  95129. this.mesh = mesh;
  95130. }
  95131. return MeshLODLevel;
  95132. }());
  95133. BABYLON.MeshLODLevel = MeshLODLevel;
  95134. })(BABYLON || (BABYLON = {}));
  95135. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95136. var BABYLON;
  95137. (function (BABYLON) {
  95138. /**
  95139. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95140. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95141. */
  95142. var SceneOptimization = /** @class */ (function () {
  95143. /**
  95144. * Creates the SceneOptimization object
  95145. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95146. * @param desc defines the description associated with the optimization
  95147. */
  95148. function SceneOptimization(
  95149. /**
  95150. * Defines the priority of this optimization (0 by default which means first in the list)
  95151. */
  95152. priority) {
  95153. if (priority === void 0) { priority = 0; }
  95154. this.priority = priority;
  95155. }
  95156. /**
  95157. * Gets a string describing the action executed by the current optimization
  95158. * @returns description string
  95159. */
  95160. SceneOptimization.prototype.getDescription = function () {
  95161. return "";
  95162. };
  95163. /**
  95164. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95165. * @param scene defines the current scene where to apply this optimization
  95166. * @param optimizer defines the current optimizer
  95167. * @returns true if everything that can be done was applied
  95168. */
  95169. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95170. return true;
  95171. };
  95172. ;
  95173. return SceneOptimization;
  95174. }());
  95175. BABYLON.SceneOptimization = SceneOptimization;
  95176. /**
  95177. * Defines an optimization used to reduce the size of render target textures
  95178. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95179. */
  95180. var TextureOptimization = /** @class */ (function (_super) {
  95181. __extends(TextureOptimization, _super);
  95182. /**
  95183. * Creates the TextureOptimization object
  95184. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95185. * @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
  95186. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95187. */
  95188. function TextureOptimization(
  95189. /**
  95190. * Defines the priority of this optimization (0 by default which means first in the list)
  95191. */
  95192. priority,
  95193. /**
  95194. * 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
  95195. */
  95196. maximumSize,
  95197. /**
  95198. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95199. */
  95200. step) {
  95201. if (priority === void 0) { priority = 0; }
  95202. if (maximumSize === void 0) { maximumSize = 1024; }
  95203. if (step === void 0) { step = 0.5; }
  95204. var _this = _super.call(this, priority) || this;
  95205. _this.priority = priority;
  95206. _this.maximumSize = maximumSize;
  95207. _this.step = step;
  95208. return _this;
  95209. }
  95210. /**
  95211. * Gets a string describing the action executed by the current optimization
  95212. * @returns description string
  95213. */
  95214. TextureOptimization.prototype.getDescription = function () {
  95215. return "Reducing render target texture size to " + this.maximumSize;
  95216. };
  95217. /**
  95218. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95219. * @param scene defines the current scene where to apply this optimization
  95220. * @param optimizer defines the current optimizer
  95221. * @returns true if everything that can be done was applied
  95222. */
  95223. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95224. var allDone = true;
  95225. for (var index = 0; index < scene.textures.length; index++) {
  95226. var texture = scene.textures[index];
  95227. if (!texture.canRescale || texture.getContext) {
  95228. continue;
  95229. }
  95230. var currentSize = texture.getSize();
  95231. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95232. if (maxDimension > this.maximumSize) {
  95233. texture.scale(this.step);
  95234. allDone = false;
  95235. }
  95236. }
  95237. return allDone;
  95238. };
  95239. return TextureOptimization;
  95240. }(SceneOptimization));
  95241. BABYLON.TextureOptimization = TextureOptimization;
  95242. /**
  95243. * Defines an optimization used to increase or decrease the rendering resolution
  95244. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95245. */
  95246. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95247. __extends(HardwareScalingOptimization, _super);
  95248. /**
  95249. * Creates the HardwareScalingOptimization object
  95250. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95251. * @param maximumScale defines the maximum scale to use (2 by default)
  95252. * @param step defines the step to use between two passes (0.5 by default)
  95253. */
  95254. function HardwareScalingOptimization(
  95255. /**
  95256. * Defines the priority of this optimization (0 by default which means first in the list)
  95257. */
  95258. priority,
  95259. /**
  95260. * Defines the maximum scale to use (2 by default)
  95261. */
  95262. maximumScale,
  95263. /**
  95264. * Defines the step to use between two passes (0.5 by default)
  95265. */
  95266. step) {
  95267. if (priority === void 0) { priority = 0; }
  95268. if (maximumScale === void 0) { maximumScale = 2; }
  95269. if (step === void 0) { step = 0.25; }
  95270. var _this = _super.call(this, priority) || this;
  95271. _this.priority = priority;
  95272. _this.maximumScale = maximumScale;
  95273. _this.step = step;
  95274. _this._currentScale = -1;
  95275. _this._directionOffset = 1;
  95276. return _this;
  95277. }
  95278. /**
  95279. * Gets a string describing the action executed by the current optimization
  95280. * @return description string
  95281. */
  95282. HardwareScalingOptimization.prototype.getDescription = function () {
  95283. return "Setting hardware scaling level to " + this._currentScale;
  95284. };
  95285. /**
  95286. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95287. * @param scene defines the current scene where to apply this optimization
  95288. * @param optimizer defines the current optimizer
  95289. * @returns true if everything that can be done was applied
  95290. */
  95291. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95292. if (this._currentScale === -1) {
  95293. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95294. if (this._currentScale > this.maximumScale) {
  95295. this._directionOffset = -1;
  95296. }
  95297. }
  95298. this._currentScale += this._directionOffset * this.step;
  95299. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95300. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95301. };
  95302. ;
  95303. return HardwareScalingOptimization;
  95304. }(SceneOptimization));
  95305. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95306. /**
  95307. * Defines an optimization used to remove shadows
  95308. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95309. */
  95310. var ShadowsOptimization = /** @class */ (function (_super) {
  95311. __extends(ShadowsOptimization, _super);
  95312. function ShadowsOptimization() {
  95313. return _super !== null && _super.apply(this, arguments) || this;
  95314. }
  95315. /**
  95316. * Gets a string describing the action executed by the current optimization
  95317. * @return description string
  95318. */
  95319. ShadowsOptimization.prototype.getDescription = function () {
  95320. return "Turning shadows on/off";
  95321. };
  95322. /**
  95323. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95324. * @param scene defines the current scene where to apply this optimization
  95325. * @param optimizer defines the current optimizer
  95326. * @returns true if everything that can be done was applied
  95327. */
  95328. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95329. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95330. return true;
  95331. };
  95332. ;
  95333. return ShadowsOptimization;
  95334. }(SceneOptimization));
  95335. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95336. /**
  95337. * Defines an optimization used to turn post-processes off
  95338. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95339. */
  95340. var PostProcessesOptimization = /** @class */ (function (_super) {
  95341. __extends(PostProcessesOptimization, _super);
  95342. function PostProcessesOptimization() {
  95343. return _super !== null && _super.apply(this, arguments) || this;
  95344. }
  95345. /**
  95346. * Gets a string describing the action executed by the current optimization
  95347. * @return description string
  95348. */
  95349. PostProcessesOptimization.prototype.getDescription = function () {
  95350. return "Turning post-processes on/off";
  95351. };
  95352. /**
  95353. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95354. * @param scene defines the current scene where to apply this optimization
  95355. * @param optimizer defines the current optimizer
  95356. * @returns true if everything that can be done was applied
  95357. */
  95358. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95359. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95360. return true;
  95361. };
  95362. ;
  95363. return PostProcessesOptimization;
  95364. }(SceneOptimization));
  95365. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95366. /**
  95367. * Defines an optimization used to turn lens flares off
  95368. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95369. */
  95370. var LensFlaresOptimization = /** @class */ (function (_super) {
  95371. __extends(LensFlaresOptimization, _super);
  95372. function LensFlaresOptimization() {
  95373. return _super !== null && _super.apply(this, arguments) || this;
  95374. }
  95375. /**
  95376. * Gets a string describing the action executed by the current optimization
  95377. * @return description string
  95378. */
  95379. LensFlaresOptimization.prototype.getDescription = function () {
  95380. return "Turning lens flares on/off";
  95381. };
  95382. /**
  95383. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95384. * @param scene defines the current scene where to apply this optimization
  95385. * @param optimizer defines the current optimizer
  95386. * @returns true if everything that can be done was applied
  95387. */
  95388. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95389. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95390. return true;
  95391. };
  95392. ;
  95393. return LensFlaresOptimization;
  95394. }(SceneOptimization));
  95395. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95396. /**
  95397. * Defines an optimization based on user defined callback.
  95398. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95399. */
  95400. var CustomOptimization = /** @class */ (function (_super) {
  95401. __extends(CustomOptimization, _super);
  95402. function CustomOptimization() {
  95403. return _super !== null && _super.apply(this, arguments) || this;
  95404. }
  95405. /**
  95406. * Gets a string describing the action executed by the current optimization
  95407. * @returns description string
  95408. */
  95409. CustomOptimization.prototype.getDescription = function () {
  95410. if (this.onGetDescription) {
  95411. return this.onGetDescription();
  95412. }
  95413. return "Running user defined callback";
  95414. };
  95415. /**
  95416. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95417. * @param scene defines the current scene where to apply this optimization
  95418. * @param optimizer defines the current optimizer
  95419. * @returns true if everything that can be done was applied
  95420. */
  95421. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95422. if (this.onApply) {
  95423. return this.onApply(scene, optimizer);
  95424. }
  95425. return true;
  95426. };
  95427. ;
  95428. return CustomOptimization;
  95429. }(SceneOptimization));
  95430. BABYLON.CustomOptimization = CustomOptimization;
  95431. /**
  95432. * Defines an optimization used to turn particles off
  95433. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95434. */
  95435. var ParticlesOptimization = /** @class */ (function (_super) {
  95436. __extends(ParticlesOptimization, _super);
  95437. function ParticlesOptimization() {
  95438. return _super !== null && _super.apply(this, arguments) || this;
  95439. }
  95440. /**
  95441. * Gets a string describing the action executed by the current optimization
  95442. * @return description string
  95443. */
  95444. ParticlesOptimization.prototype.getDescription = function () {
  95445. return "Turning particles on/off";
  95446. };
  95447. /**
  95448. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95449. * @param scene defines the current scene where to apply this optimization
  95450. * @param optimizer defines the current optimizer
  95451. * @returns true if everything that can be done was applied
  95452. */
  95453. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95454. scene.particlesEnabled = optimizer.isInImprovementMode;
  95455. return true;
  95456. };
  95457. ;
  95458. return ParticlesOptimization;
  95459. }(SceneOptimization));
  95460. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95461. /**
  95462. * Defines an optimization used to turn render targets off
  95463. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95464. */
  95465. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95466. __extends(RenderTargetsOptimization, _super);
  95467. function RenderTargetsOptimization() {
  95468. return _super !== null && _super.apply(this, arguments) || this;
  95469. }
  95470. /**
  95471. * Gets a string describing the action executed by the current optimization
  95472. * @return description string
  95473. */
  95474. RenderTargetsOptimization.prototype.getDescription = function () {
  95475. return "Turning render targets off";
  95476. };
  95477. /**
  95478. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95479. * @param scene defines the current scene where to apply this optimization
  95480. * @param optimizer defines the current optimizer
  95481. * @returns true if everything that can be done was applied
  95482. */
  95483. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95484. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95485. return true;
  95486. };
  95487. ;
  95488. return RenderTargetsOptimization;
  95489. }(SceneOptimization));
  95490. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95491. /**
  95492. * Defines an optimization used to merge meshes with compatible materials
  95493. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95494. */
  95495. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95496. __extends(MergeMeshesOptimization, _super);
  95497. function MergeMeshesOptimization() {
  95498. var _this = _super !== null && _super.apply(this, arguments) || this;
  95499. _this._canBeMerged = function (abstractMesh) {
  95500. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95501. return false;
  95502. }
  95503. var mesh = abstractMesh;
  95504. if (mesh.isDisposed()) {
  95505. return false;
  95506. }
  95507. if (!mesh.isVisible || !mesh.isEnabled()) {
  95508. return false;
  95509. }
  95510. if (mesh.instances.length > 0) {
  95511. return false;
  95512. }
  95513. if (mesh.skeleton || mesh.hasLODLevels) {
  95514. return false;
  95515. }
  95516. return true;
  95517. };
  95518. return _this;
  95519. }
  95520. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95521. /**
  95522. * Gets or sets a boolean which defines if optimization octree has to be updated
  95523. */
  95524. get: function () {
  95525. return MergeMeshesOptimization._UpdateSelectionTree;
  95526. },
  95527. /**
  95528. * Gets or sets a boolean which defines if optimization octree has to be updated
  95529. */
  95530. set: function (value) {
  95531. MergeMeshesOptimization._UpdateSelectionTree = value;
  95532. },
  95533. enumerable: true,
  95534. configurable: true
  95535. });
  95536. /**
  95537. * Gets a string describing the action executed by the current optimization
  95538. * @return description string
  95539. */
  95540. MergeMeshesOptimization.prototype.getDescription = function () {
  95541. return "Merging similar meshes together";
  95542. };
  95543. /**
  95544. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95545. * @param scene defines the current scene where to apply this optimization
  95546. * @param optimizer defines the current optimizer
  95547. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95548. * @returns true if everything that can be done was applied
  95549. */
  95550. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95551. var globalPool = scene.meshes.slice(0);
  95552. var globalLength = globalPool.length;
  95553. for (var index = 0; index < globalLength; index++) {
  95554. var currentPool = new Array();
  95555. var current = globalPool[index];
  95556. // Checks
  95557. if (!this._canBeMerged(current)) {
  95558. continue;
  95559. }
  95560. currentPool.push(current);
  95561. // Find compatible meshes
  95562. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95563. var otherMesh = globalPool[subIndex];
  95564. if (!this._canBeMerged(otherMesh)) {
  95565. continue;
  95566. }
  95567. if (otherMesh.material !== current.material) {
  95568. continue;
  95569. }
  95570. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95571. continue;
  95572. }
  95573. currentPool.push(otherMesh);
  95574. globalLength--;
  95575. globalPool.splice(subIndex, 1);
  95576. subIndex--;
  95577. }
  95578. if (currentPool.length < 2) {
  95579. continue;
  95580. }
  95581. // Merge meshes
  95582. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95583. }
  95584. if (updateSelectionTree != undefined) {
  95585. if (updateSelectionTree) {
  95586. scene.createOrUpdateSelectionOctree();
  95587. }
  95588. }
  95589. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95590. scene.createOrUpdateSelectionOctree();
  95591. }
  95592. return true;
  95593. };
  95594. ;
  95595. MergeMeshesOptimization._UpdateSelectionTree = false;
  95596. return MergeMeshesOptimization;
  95597. }(SceneOptimization));
  95598. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95599. /**
  95600. * Defines a list of options used by SceneOptimizer
  95601. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95602. */
  95603. var SceneOptimizerOptions = /** @class */ (function () {
  95604. /**
  95605. * Creates a new list of options used by SceneOptimizer
  95606. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95607. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95608. */
  95609. function SceneOptimizerOptions(
  95610. /**
  95611. * Defines the target frame rate to reach (60 by default)
  95612. */
  95613. targetFrameRate,
  95614. /**
  95615. * Defines the interval between two checkes (2000ms by default)
  95616. */
  95617. trackerDuration) {
  95618. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95619. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95620. this.targetFrameRate = targetFrameRate;
  95621. this.trackerDuration = trackerDuration;
  95622. /**
  95623. * Gets the list of optimizations to apply
  95624. */
  95625. this.optimizations = new Array();
  95626. }
  95627. /**
  95628. * Add a new optimization
  95629. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95630. * @returns the current SceneOptimizerOptions
  95631. */
  95632. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95633. this.optimizations.push(optimization);
  95634. return this;
  95635. };
  95636. /**
  95637. * Add a new custom optimization
  95638. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95639. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95640. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95641. * @returns the current SceneOptimizerOptions
  95642. */
  95643. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95644. if (priority === void 0) { priority = 0; }
  95645. var optimization = new CustomOptimization(priority);
  95646. optimization.onApply = onApply;
  95647. optimization.onGetDescription = onGetDescription;
  95648. this.optimizations.push(optimization);
  95649. return this;
  95650. };
  95651. /**
  95652. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95653. * @param targetFrameRate defines the target frame rate (60 by default)
  95654. * @returns a SceneOptimizerOptions object
  95655. */
  95656. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95657. var result = new SceneOptimizerOptions(targetFrameRate);
  95658. var priority = 0;
  95659. result.addOptimization(new MergeMeshesOptimization(priority));
  95660. result.addOptimization(new ShadowsOptimization(priority));
  95661. result.addOptimization(new LensFlaresOptimization(priority));
  95662. // Next priority
  95663. priority++;
  95664. result.addOptimization(new PostProcessesOptimization(priority));
  95665. result.addOptimization(new ParticlesOptimization(priority));
  95666. // Next priority
  95667. priority++;
  95668. result.addOptimization(new TextureOptimization(priority, 1024));
  95669. return result;
  95670. };
  95671. /**
  95672. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95673. * @param targetFrameRate defines the target frame rate (60 by default)
  95674. * @returns a SceneOptimizerOptions object
  95675. */
  95676. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95677. var result = new SceneOptimizerOptions(targetFrameRate);
  95678. var priority = 0;
  95679. result.addOptimization(new MergeMeshesOptimization(priority));
  95680. result.addOptimization(new ShadowsOptimization(priority));
  95681. result.addOptimization(new LensFlaresOptimization(priority));
  95682. // Next priority
  95683. priority++;
  95684. result.addOptimization(new PostProcessesOptimization(priority));
  95685. result.addOptimization(new ParticlesOptimization(priority));
  95686. // Next priority
  95687. priority++;
  95688. result.addOptimization(new TextureOptimization(priority, 512));
  95689. // Next priority
  95690. priority++;
  95691. result.addOptimization(new RenderTargetsOptimization(priority));
  95692. // Next priority
  95693. priority++;
  95694. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95695. return result;
  95696. };
  95697. /**
  95698. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95699. * @param targetFrameRate defines the target frame rate (60 by default)
  95700. * @returns a SceneOptimizerOptions object
  95701. */
  95702. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95703. var result = new SceneOptimizerOptions(targetFrameRate);
  95704. var priority = 0;
  95705. result.addOptimization(new MergeMeshesOptimization(priority));
  95706. result.addOptimization(new ShadowsOptimization(priority));
  95707. result.addOptimization(new LensFlaresOptimization(priority));
  95708. // Next priority
  95709. priority++;
  95710. result.addOptimization(new PostProcessesOptimization(priority));
  95711. result.addOptimization(new ParticlesOptimization(priority));
  95712. // Next priority
  95713. priority++;
  95714. result.addOptimization(new TextureOptimization(priority, 256));
  95715. // Next priority
  95716. priority++;
  95717. result.addOptimization(new RenderTargetsOptimization(priority));
  95718. // Next priority
  95719. priority++;
  95720. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95721. return result;
  95722. };
  95723. return SceneOptimizerOptions;
  95724. }());
  95725. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95726. /**
  95727. * Class used to run optimizations in order to reach a target frame rate
  95728. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95729. */
  95730. var SceneOptimizer = /** @class */ (function () {
  95731. /**
  95732. * Creates a new SceneOptimizer
  95733. * @param scene defines the scene to work on
  95734. * @param options defines the options to use with the SceneOptimizer
  95735. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95736. * @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)
  95737. */
  95738. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95739. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95740. if (improvementMode === void 0) { improvementMode = false; }
  95741. var _this = this;
  95742. this._isRunning = false;
  95743. this._currentPriorityLevel = 0;
  95744. this._targetFrameRate = 60;
  95745. this._trackerDuration = 2000;
  95746. this._currentFrameRate = 0;
  95747. this._improvementMode = false;
  95748. /**
  95749. * Defines an observable called when the optimizer reaches the target frame rate
  95750. */
  95751. this.onSuccessObservable = new BABYLON.Observable();
  95752. /**
  95753. * Defines an observable called when the optimizer enables an optimization
  95754. */
  95755. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95756. /**
  95757. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95758. */
  95759. this.onFailureObservable = new BABYLON.Observable();
  95760. if (!options) {
  95761. this._options = new SceneOptimizerOptions();
  95762. }
  95763. else {
  95764. this._options = options;
  95765. }
  95766. if (this._options.targetFrameRate) {
  95767. this._targetFrameRate = this._options.targetFrameRate;
  95768. }
  95769. if (this._options.trackerDuration) {
  95770. this._trackerDuration = this._options.trackerDuration;
  95771. }
  95772. if (autoGeneratePriorities) {
  95773. var priority = 0;
  95774. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95775. var optim = _a[_i];
  95776. optim.priority = priority++;
  95777. }
  95778. }
  95779. this._improvementMode = improvementMode;
  95780. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95781. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95782. _this._sceneDisposeObserver = null;
  95783. _this.dispose();
  95784. });
  95785. }
  95786. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95787. /**
  95788. * Gets a boolean indicating if the optimizer is in improvement mode
  95789. */
  95790. get: function () {
  95791. return this._improvementMode;
  95792. },
  95793. enumerable: true,
  95794. configurable: true
  95795. });
  95796. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95797. /**
  95798. * Gets the current priority level (0 at start)
  95799. */
  95800. get: function () {
  95801. return this._currentPriorityLevel;
  95802. },
  95803. enumerable: true,
  95804. configurable: true
  95805. });
  95806. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95807. /**
  95808. * Gets the current frame rate checked by the SceneOptimizer
  95809. */
  95810. get: function () {
  95811. return this._currentFrameRate;
  95812. },
  95813. enumerable: true,
  95814. configurable: true
  95815. });
  95816. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95817. /**
  95818. * Gets or sets the current target frame rate (60 by default)
  95819. */
  95820. get: function () {
  95821. return this._targetFrameRate;
  95822. },
  95823. /**
  95824. * Gets or sets the current target frame rate (60 by default)
  95825. */
  95826. set: function (value) {
  95827. this._targetFrameRate = value;
  95828. },
  95829. enumerable: true,
  95830. configurable: true
  95831. });
  95832. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95833. /**
  95834. * Gets or sets the current interval between two checks (every 2000ms by default)
  95835. */
  95836. get: function () {
  95837. return this._trackerDuration;
  95838. },
  95839. /**
  95840. * Gets or sets the current interval between two checks (every 2000ms by default)
  95841. */
  95842. set: function (value) {
  95843. this._trackerDuration = value;
  95844. },
  95845. enumerable: true,
  95846. configurable: true
  95847. });
  95848. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95849. /**
  95850. * Gets the list of active optimizations
  95851. */
  95852. get: function () {
  95853. return this._options.optimizations;
  95854. },
  95855. enumerable: true,
  95856. configurable: true
  95857. });
  95858. /**
  95859. * Stops the current optimizer
  95860. */
  95861. SceneOptimizer.prototype.stop = function () {
  95862. this._isRunning = false;
  95863. };
  95864. /**
  95865. * Reset the optimizer to initial step (current priority level = 0)
  95866. */
  95867. SceneOptimizer.prototype.reset = function () {
  95868. this._currentPriorityLevel = 0;
  95869. };
  95870. /**
  95871. * Start the optimizer. By default it will try to reach a specific framerate
  95872. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95873. */
  95874. SceneOptimizer.prototype.start = function () {
  95875. var _this = this;
  95876. if (this._isRunning) {
  95877. return;
  95878. }
  95879. this._isRunning = true;
  95880. // Let's wait for the scene to be ready before running our check
  95881. this._scene.executeWhenReady(function () {
  95882. setTimeout(function () {
  95883. _this._checkCurrentState();
  95884. }, _this._trackerDuration);
  95885. });
  95886. };
  95887. SceneOptimizer.prototype._checkCurrentState = function () {
  95888. var _this = this;
  95889. if (!this._isRunning) {
  95890. return;
  95891. }
  95892. var scene = this._scene;
  95893. var options = this._options;
  95894. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95895. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95896. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95897. this._isRunning = false;
  95898. this.onSuccessObservable.notifyObservers(this);
  95899. return;
  95900. }
  95901. // Apply current level of optimizations
  95902. var allDone = true;
  95903. var noOptimizationApplied = true;
  95904. for (var index = 0; index < options.optimizations.length; index++) {
  95905. var optimization = options.optimizations[index];
  95906. if (optimization.priority === this._currentPriorityLevel) {
  95907. noOptimizationApplied = false;
  95908. allDone = allDone && optimization.apply(scene, this);
  95909. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95910. }
  95911. }
  95912. // If no optimization was applied, this is a failure :(
  95913. if (noOptimizationApplied) {
  95914. this._isRunning = false;
  95915. this.onFailureObservable.notifyObservers(this);
  95916. return;
  95917. }
  95918. // If all optimizations were done, move to next level
  95919. if (allDone) {
  95920. this._currentPriorityLevel++;
  95921. }
  95922. // Let's the system running for a specific amount of time before checking FPS
  95923. scene.executeWhenReady(function () {
  95924. setTimeout(function () {
  95925. _this._checkCurrentState();
  95926. }, _this._trackerDuration);
  95927. });
  95928. };
  95929. /**
  95930. * Release all resources
  95931. */
  95932. SceneOptimizer.prototype.dispose = function () {
  95933. this.stop();
  95934. this.onSuccessObservable.clear();
  95935. this.onFailureObservable.clear();
  95936. this.onNewOptimizationAppliedObservable.clear();
  95937. if (this._sceneDisposeObserver) {
  95938. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95939. }
  95940. };
  95941. /**
  95942. * Helper function to create a SceneOptimizer with one single line of code
  95943. * @param scene defines the scene to work on
  95944. * @param options defines the options to use with the SceneOptimizer
  95945. * @param onSuccess defines a callback to call on success
  95946. * @param onFailure defines a callback to call on failure
  95947. * @returns the new SceneOptimizer object
  95948. */
  95949. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95950. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95951. if (onSuccess) {
  95952. optimizer.onSuccessObservable.add(function () {
  95953. onSuccess();
  95954. });
  95955. }
  95956. if (onFailure) {
  95957. optimizer.onFailureObservable.add(function () {
  95958. onFailure();
  95959. });
  95960. }
  95961. optimizer.start();
  95962. return optimizer;
  95963. };
  95964. return SceneOptimizer;
  95965. }());
  95966. BABYLON.SceneOptimizer = SceneOptimizer;
  95967. })(BABYLON || (BABYLON = {}));
  95968. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95969. var BABYLON;
  95970. (function (BABYLON) {
  95971. var OutlineRenderer = /** @class */ (function () {
  95972. function OutlineRenderer(scene) {
  95973. this.zOffset = 1;
  95974. this._scene = scene;
  95975. }
  95976. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95977. var _this = this;
  95978. if (useOverlay === void 0) { useOverlay = false; }
  95979. var scene = this._scene;
  95980. var engine = this._scene.getEngine();
  95981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95982. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95983. return;
  95984. }
  95985. var mesh = subMesh.getRenderingMesh();
  95986. var material = subMesh.getMaterial();
  95987. if (!material || !scene.activeCamera) {
  95988. return;
  95989. }
  95990. engine.enableEffect(this._effect);
  95991. // Logarithmic depth
  95992. if (material.useLogarithmicDepth) {
  95993. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95994. }
  95995. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95996. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95997. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95998. // Bones
  95999. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96000. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96001. }
  96002. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96003. // Alpha test
  96004. if (material && material.needAlphaTesting()) {
  96005. var alphaTexture = material.getAlphaTestTexture();
  96006. if (alphaTexture) {
  96007. this._effect.setTexture("diffuseSampler", alphaTexture);
  96008. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96009. }
  96010. }
  96011. engine.setZOffset(-this.zOffset);
  96012. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96013. engine.setZOffset(0);
  96014. };
  96015. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96016. var defines = [];
  96017. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96018. var mesh = subMesh.getMesh();
  96019. var material = subMesh.getMaterial();
  96020. if (material) {
  96021. // Alpha test
  96022. if (material.needAlphaTesting()) {
  96023. defines.push("#define ALPHATEST");
  96024. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96025. attribs.push(BABYLON.VertexBuffer.UVKind);
  96026. defines.push("#define UV1");
  96027. }
  96028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96030. defines.push("#define UV2");
  96031. }
  96032. }
  96033. //Logarithmic depth
  96034. if (material.useLogarithmicDepth) {
  96035. defines.push("#define LOGARITHMICDEPTH");
  96036. }
  96037. }
  96038. // Bones
  96039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96042. if (mesh.numBoneInfluencers > 4) {
  96043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96045. }
  96046. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96047. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96048. }
  96049. else {
  96050. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96051. }
  96052. // Instances
  96053. if (useInstances) {
  96054. defines.push("#define INSTANCES");
  96055. attribs.push("world0");
  96056. attribs.push("world1");
  96057. attribs.push("world2");
  96058. attribs.push("world3");
  96059. }
  96060. // Get correct effect
  96061. var join = defines.join("\n");
  96062. if (this._cachedDefines !== join) {
  96063. this._cachedDefines = join;
  96064. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96065. }
  96066. return this._effect.isReady();
  96067. };
  96068. return OutlineRenderer;
  96069. }());
  96070. BABYLON.OutlineRenderer = OutlineRenderer;
  96071. })(BABYLON || (BABYLON = {}));
  96072. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96073. var BABYLON;
  96074. (function (BABYLON) {
  96075. var FaceAdjacencies = /** @class */ (function () {
  96076. function FaceAdjacencies() {
  96077. this.edges = new Array();
  96078. this.edgesConnectedCount = 0;
  96079. }
  96080. return FaceAdjacencies;
  96081. }());
  96082. var EdgesRenderer = /** @class */ (function () {
  96083. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96084. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96085. if (epsilon === void 0) { epsilon = 0.95; }
  96086. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96087. this.edgesWidthScalerForOrthographic = 1000.0;
  96088. this.edgesWidthScalerForPerspective = 50.0;
  96089. this._linesPositions = new Array();
  96090. this._linesNormals = new Array();
  96091. this._linesIndices = new Array();
  96092. this._buffers = {};
  96093. this._checkVerticesInsteadOfIndices = false;
  96094. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96095. this.isEnabled = true;
  96096. this._source = source;
  96097. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96098. this._epsilon = epsilon;
  96099. this._prepareRessources();
  96100. this._generateEdgesLines();
  96101. }
  96102. EdgesRenderer.prototype._prepareRessources = function () {
  96103. if (this._lineShader) {
  96104. return;
  96105. }
  96106. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96107. attributes: ["position", "normal"],
  96108. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96109. });
  96110. this._lineShader.disableDepthWrite = true;
  96111. this._lineShader.backFaceCulling = false;
  96112. };
  96113. EdgesRenderer.prototype._rebuild = function () {
  96114. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96115. if (buffer) {
  96116. buffer._rebuild();
  96117. }
  96118. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96119. if (buffer) {
  96120. buffer._rebuild();
  96121. }
  96122. var scene = this._source.getScene();
  96123. var engine = scene.getEngine();
  96124. this._ib = engine.createIndexBuffer(this._linesIndices);
  96125. };
  96126. EdgesRenderer.prototype.dispose = function () {
  96127. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96128. if (buffer) {
  96129. buffer.dispose();
  96130. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96131. }
  96132. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96133. if (buffer) {
  96134. buffer.dispose();
  96135. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96136. }
  96137. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96138. this._lineShader.dispose();
  96139. };
  96140. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96141. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96142. return 0;
  96143. }
  96144. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96145. return 1;
  96146. }
  96147. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96148. return 2;
  96149. }
  96150. return -1;
  96151. };
  96152. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96153. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96154. return 0;
  96155. }
  96156. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96157. return 1;
  96158. }
  96159. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96160. return 2;
  96161. }
  96162. return -1;
  96163. };
  96164. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96165. var needToCreateLine;
  96166. if (edge === undefined) {
  96167. needToCreateLine = true;
  96168. }
  96169. else {
  96170. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96171. needToCreateLine = dotProduct < this._epsilon;
  96172. }
  96173. if (needToCreateLine) {
  96174. var offset = this._linesPositions.length / 3;
  96175. var normal = p0.subtract(p1);
  96176. normal.normalize();
  96177. // Positions
  96178. this._linesPositions.push(p0.x);
  96179. this._linesPositions.push(p0.y);
  96180. this._linesPositions.push(p0.z);
  96181. this._linesPositions.push(p0.x);
  96182. this._linesPositions.push(p0.y);
  96183. this._linesPositions.push(p0.z);
  96184. this._linesPositions.push(p1.x);
  96185. this._linesPositions.push(p1.y);
  96186. this._linesPositions.push(p1.z);
  96187. this._linesPositions.push(p1.x);
  96188. this._linesPositions.push(p1.y);
  96189. this._linesPositions.push(p1.z);
  96190. // Normals
  96191. this._linesNormals.push(p1.x);
  96192. this._linesNormals.push(p1.y);
  96193. this._linesNormals.push(p1.z);
  96194. this._linesNormals.push(-1);
  96195. this._linesNormals.push(p1.x);
  96196. this._linesNormals.push(p1.y);
  96197. this._linesNormals.push(p1.z);
  96198. this._linesNormals.push(1);
  96199. this._linesNormals.push(p0.x);
  96200. this._linesNormals.push(p0.y);
  96201. this._linesNormals.push(p0.z);
  96202. this._linesNormals.push(-1);
  96203. this._linesNormals.push(p0.x);
  96204. this._linesNormals.push(p0.y);
  96205. this._linesNormals.push(p0.z);
  96206. this._linesNormals.push(1);
  96207. // Indices
  96208. this._linesIndices.push(offset);
  96209. this._linesIndices.push(offset + 1);
  96210. this._linesIndices.push(offset + 2);
  96211. this._linesIndices.push(offset);
  96212. this._linesIndices.push(offset + 2);
  96213. this._linesIndices.push(offset + 3);
  96214. }
  96215. };
  96216. EdgesRenderer.prototype._generateEdgesLines = function () {
  96217. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96218. var indices = this._source.getIndices();
  96219. if (!indices || !positions) {
  96220. return;
  96221. }
  96222. // First let's find adjacencies
  96223. var adjacencies = new Array();
  96224. var faceNormals = new Array();
  96225. var index;
  96226. var faceAdjacencies;
  96227. // Prepare faces
  96228. for (index = 0; index < indices.length; index += 3) {
  96229. faceAdjacencies = new FaceAdjacencies();
  96230. var p0Index = indices[index];
  96231. var p1Index = indices[index + 1];
  96232. var p2Index = indices[index + 2];
  96233. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96234. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96235. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96236. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96237. faceNormal.normalize();
  96238. faceNormals.push(faceNormal);
  96239. adjacencies.push(faceAdjacencies);
  96240. }
  96241. // Scan
  96242. for (index = 0; index < adjacencies.length; index++) {
  96243. faceAdjacencies = adjacencies[index];
  96244. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96245. var otherFaceAdjacencies = adjacencies[otherIndex];
  96246. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96247. break;
  96248. }
  96249. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96250. continue;
  96251. }
  96252. var otherP0 = indices[otherIndex * 3];
  96253. var otherP1 = indices[otherIndex * 3 + 1];
  96254. var otherP2 = indices[otherIndex * 3 + 2];
  96255. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96256. var otherEdgeIndex = 0;
  96257. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96258. continue;
  96259. }
  96260. switch (edgeIndex) {
  96261. case 0:
  96262. if (this._checkVerticesInsteadOfIndices) {
  96263. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96264. }
  96265. else {
  96266. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96267. }
  96268. break;
  96269. case 1:
  96270. if (this._checkVerticesInsteadOfIndices) {
  96271. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96272. }
  96273. else {
  96274. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96275. }
  96276. break;
  96277. case 2:
  96278. if (this._checkVerticesInsteadOfIndices) {
  96279. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96280. }
  96281. else {
  96282. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96283. }
  96284. break;
  96285. }
  96286. if (otherEdgeIndex === -1) {
  96287. continue;
  96288. }
  96289. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96290. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96291. faceAdjacencies.edgesConnectedCount++;
  96292. otherFaceAdjacencies.edgesConnectedCount++;
  96293. if (faceAdjacencies.edgesConnectedCount === 3) {
  96294. break;
  96295. }
  96296. }
  96297. }
  96298. }
  96299. // Create lines
  96300. for (index = 0; index < adjacencies.length; index++) {
  96301. // 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
  96302. var current = adjacencies[index];
  96303. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96304. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96305. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96306. }
  96307. // Merge into a single mesh
  96308. var engine = this._source.getScene().getEngine();
  96309. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96310. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96311. this._ib = engine.createIndexBuffer(this._linesIndices);
  96312. this._indicesCount = this._linesIndices.length;
  96313. };
  96314. EdgesRenderer.prototype.render = function () {
  96315. var scene = this._source.getScene();
  96316. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96317. return;
  96318. }
  96319. var engine = scene.getEngine();
  96320. this._lineShader._preBind();
  96321. // VBOs
  96322. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96323. scene.resetCachedMaterial();
  96324. this._lineShader.setColor4("color", this._source.edgesColor);
  96325. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96326. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96327. }
  96328. else {
  96329. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96330. }
  96331. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96332. this._lineShader.bind(this._source.getWorldMatrix());
  96333. // Draw order
  96334. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96335. this._lineShader.unbind();
  96336. engine.setDepthWrite(true);
  96337. };
  96338. return EdgesRenderer;
  96339. }());
  96340. BABYLON.EdgesRenderer = EdgesRenderer;
  96341. })(BABYLON || (BABYLON = {}));
  96342. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96343. var BABYLON;
  96344. (function (BABYLON) {
  96345. // Adds the parser to the scene parsers.
  96346. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96347. if (parsedData.effectLayers) {
  96348. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96349. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96350. container.effectLayers.push(effectLayer);
  96351. }
  96352. }
  96353. });
  96354. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96355. var index = this.effectLayers.indexOf(toRemove);
  96356. if (index !== -1) {
  96357. this.effectLayers.splice(index, 1);
  96358. }
  96359. return index;
  96360. };
  96361. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96362. this.effectLayers.push(newEffectLayer);
  96363. };
  96364. /**
  96365. * Defines the layer scene component responsible to manage any effect layers
  96366. * in a given scene.
  96367. */
  96368. var EffectLayerSceneComponent = /** @class */ (function () {
  96369. /**
  96370. * Creates a new instance of the component for the given scene
  96371. * @param scene Defines the scene to register the component in
  96372. */
  96373. function EffectLayerSceneComponent(scene) {
  96374. /**
  96375. * The component name helpfull to identify the component in the list of scene components.
  96376. */
  96377. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96378. this._renderEffects = false;
  96379. this._needStencil = false;
  96380. this._previousStencilState = false;
  96381. this.scene = scene;
  96382. this._engine = scene.getEngine();
  96383. scene.effectLayers = new Array();
  96384. }
  96385. /**
  96386. * Registers the component in a given scene
  96387. */
  96388. EffectLayerSceneComponent.prototype.register = function () {
  96389. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96390. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96391. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96392. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96393. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96394. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96395. };
  96396. /**
  96397. * Rebuilds the elements related to this component in case of
  96398. * context lost for instance.
  96399. */
  96400. EffectLayerSceneComponent.prototype.rebuild = function () {
  96401. var layers = this.scene.effectLayers;
  96402. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96403. var effectLayer = layers_1[_i];
  96404. effectLayer._rebuild();
  96405. }
  96406. };
  96407. /**
  96408. * Serializes the component data to the specified json object
  96409. * @param serializationObject The object to serialize to
  96410. */
  96411. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96412. // Effect layers
  96413. serializationObject.effectLayers = [];
  96414. var layers = this.scene.effectLayers;
  96415. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96416. var effectLayer = layers_2[_i];
  96417. if (effectLayer.serialize) {
  96418. serializationObject.effectLayers.push(effectLayer.serialize());
  96419. }
  96420. }
  96421. };
  96422. /**
  96423. * Adds all the element from the container to the scene
  96424. * @param container the container holding the elements
  96425. */
  96426. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96427. var _this = this;
  96428. if (!container.effectLayers) {
  96429. return;
  96430. }
  96431. container.effectLayers.forEach(function (o) {
  96432. _this.scene.addEffectLayer(o);
  96433. });
  96434. };
  96435. /**
  96436. * Removes all the elements in the container from the scene
  96437. * @param container contains the elements to remove
  96438. */
  96439. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96440. var _this = this;
  96441. if (!container.effectLayers) {
  96442. return;
  96443. }
  96444. container.effectLayers.forEach(function (o) {
  96445. _this.scene.removeEffectLayer(o);
  96446. });
  96447. };
  96448. /**
  96449. * Disposes the component and the associated ressources.
  96450. */
  96451. EffectLayerSceneComponent.prototype.dispose = function () {
  96452. var layers = this.scene.effectLayers;
  96453. while (layers.length) {
  96454. layers[0].dispose();
  96455. }
  96456. };
  96457. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96458. var layers = this.scene.effectLayers;
  96459. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96460. var layer = layers_3[_i];
  96461. if (!layer.hasMesh(mesh)) {
  96462. continue;
  96463. }
  96464. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96465. var subMesh = _b[_a];
  96466. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96467. return false;
  96468. }
  96469. }
  96470. }
  96471. return true;
  96472. };
  96473. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96474. this._renderEffects = false;
  96475. this._needStencil = false;
  96476. var layers = this.scene.effectLayers;
  96477. if (layers && layers.length > 0) {
  96478. this._previousStencilState = this._engine.getStencilBuffer();
  96479. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96480. var effectLayer = layers_4[_i];
  96481. if (effectLayer.shouldRender() &&
  96482. (!effectLayer.camera ||
  96483. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96484. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96485. this._renderEffects = true;
  96486. this._needStencil = this._needStencil || effectLayer.needStencil();
  96487. var renderTarget = effectLayer._mainTexture;
  96488. if (renderTarget._shouldRender()) {
  96489. this.scene.incrementRenderId();
  96490. renderTarget.render(false, false);
  96491. }
  96492. }
  96493. }
  96494. this.scene.incrementRenderId();
  96495. }
  96496. };
  96497. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96498. // Activate effect Layer stencil
  96499. if (this._needStencil) {
  96500. this._engine.setStencilBuffer(true);
  96501. }
  96502. };
  96503. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96504. // Restore effect Layer stencil
  96505. if (this._needStencil) {
  96506. this._engine.setStencilBuffer(this._previousStencilState);
  96507. }
  96508. };
  96509. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96510. if (this._renderEffects) {
  96511. this._engine.setDepthBuffer(false);
  96512. var layers = this.scene.effectLayers;
  96513. for (var i = 0; i < layers.length; i++) {
  96514. var effectLayer = layers[i];
  96515. if (effectLayer.renderingGroupId === renderingGroupId) {
  96516. if (effectLayer.shouldRender()) {
  96517. effectLayer.render();
  96518. }
  96519. }
  96520. }
  96521. this._engine.setDepthBuffer(true);
  96522. }
  96523. };
  96524. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96525. if (this._renderEffects) {
  96526. this._draw(-1);
  96527. }
  96528. };
  96529. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96530. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96531. this._draw(index);
  96532. }
  96533. };
  96534. return EffectLayerSceneComponent;
  96535. }());
  96536. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96537. })(BABYLON || (BABYLON = {}));
  96538. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96539. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96540. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96541. s = arguments[i];
  96542. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96543. t[p] = s[p];
  96544. }
  96545. return t;
  96546. };
  96547. var BABYLON;
  96548. (function (BABYLON) {
  96549. /**
  96550. * The effect layer Helps adding post process effect blended with the main pass.
  96551. *
  96552. * This can be for instance use to generate glow or higlight effects on the scene.
  96553. *
  96554. * The effect layer class can not be used directly and is intented to inherited from to be
  96555. * customized per effects.
  96556. */
  96557. var EffectLayer = /** @class */ (function () {
  96558. /**
  96559. * Instantiates a new effect Layer and references it in the scene.
  96560. * @param name The name of the layer
  96561. * @param scene The scene to use the layer in
  96562. */
  96563. function EffectLayer(
  96564. /** The Friendly of the effect in the scene */
  96565. name, scene) {
  96566. this._vertexBuffers = {};
  96567. this._maxSize = 0;
  96568. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96569. this._shouldRender = true;
  96570. this._postProcesses = [];
  96571. this._textures = [];
  96572. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96573. /**
  96574. * The clear color of the texture used to generate the glow map.
  96575. */
  96576. this.neutralColor = new BABYLON.Color4();
  96577. /**
  96578. * Specifies wether the highlight layer is enabled or not.
  96579. */
  96580. this.isEnabled = true;
  96581. /**
  96582. * An event triggered when the effect layer has been disposed.
  96583. */
  96584. this.onDisposeObservable = new BABYLON.Observable();
  96585. /**
  96586. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96587. */
  96588. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96589. /**
  96590. * An event triggered when the generated texture is being merged in the scene.
  96591. */
  96592. this.onBeforeComposeObservable = new BABYLON.Observable();
  96593. /**
  96594. * An event triggered when the generated texture has been merged in the scene.
  96595. */
  96596. this.onAfterComposeObservable = new BABYLON.Observable();
  96597. /**
  96598. * An event triggered when the efffect layer changes its size.
  96599. */
  96600. this.onSizeChangedObservable = new BABYLON.Observable();
  96601. this.name = name;
  96602. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96603. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96604. if (!component) {
  96605. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96606. this._scene._addComponent(component);
  96607. }
  96608. this._engine = this._scene.getEngine();
  96609. this._maxSize = this._engine.getCaps().maxTextureSize;
  96610. this._scene.effectLayers.push(this);
  96611. // Generate Buffers
  96612. this._generateIndexBuffer();
  96613. this._genrateVertexBuffer();
  96614. }
  96615. Object.defineProperty(EffectLayer.prototype, "camera", {
  96616. /**
  96617. * Gets the camera attached to the layer.
  96618. */
  96619. get: function () {
  96620. return this._effectLayerOptions.camera;
  96621. },
  96622. enumerable: true,
  96623. configurable: true
  96624. });
  96625. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96626. /**
  96627. * Gets the rendering group id the layer should render in.
  96628. */
  96629. get: function () {
  96630. return this._effectLayerOptions.renderingGroupId;
  96631. },
  96632. enumerable: true,
  96633. configurable: true
  96634. });
  96635. /**
  96636. * Initializes the effect layer with the required options.
  96637. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96638. */
  96639. EffectLayer.prototype._init = function (options) {
  96640. // Adapt options
  96641. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96642. this._setMainTextureSize();
  96643. this._createMainTexture();
  96644. this._createTextureAndPostProcesses();
  96645. this._mergeEffect = this._createMergeEffect();
  96646. };
  96647. /**
  96648. * Generates the index buffer of the full screen quad blending to the main canvas.
  96649. */
  96650. EffectLayer.prototype._generateIndexBuffer = function () {
  96651. // Indices
  96652. var indices = [];
  96653. indices.push(0);
  96654. indices.push(1);
  96655. indices.push(2);
  96656. indices.push(0);
  96657. indices.push(2);
  96658. indices.push(3);
  96659. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96660. };
  96661. /**
  96662. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96663. */
  96664. EffectLayer.prototype._genrateVertexBuffer = function () {
  96665. // VBO
  96666. var vertices = [];
  96667. vertices.push(1, 1);
  96668. vertices.push(-1, 1);
  96669. vertices.push(-1, -1);
  96670. vertices.push(1, -1);
  96671. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96672. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96673. };
  96674. /**
  96675. * Sets the main texture desired size which is the closest power of two
  96676. * of the engine canvas size.
  96677. */
  96678. EffectLayer.prototype._setMainTextureSize = function () {
  96679. if (this._effectLayerOptions.mainTextureFixedSize) {
  96680. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96681. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96682. }
  96683. else {
  96684. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96685. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96686. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96687. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96688. }
  96689. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96690. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96691. };
  96692. /**
  96693. * Creates the main texture for the effect layer.
  96694. */
  96695. EffectLayer.prototype._createMainTexture = function () {
  96696. var _this = this;
  96697. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96698. width: this._mainTextureDesiredSize.width,
  96699. height: this._mainTextureDesiredSize.height
  96700. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96701. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96702. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96703. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96704. this._mainTexture.anisotropicFilteringLevel = 1;
  96705. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96706. this._mainTexture.renderParticles = false;
  96707. this._mainTexture.renderList = null;
  96708. this._mainTexture.ignoreCameraViewport = true;
  96709. // Custom render function
  96710. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96711. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96712. var index;
  96713. var engine = _this._scene.getEngine();
  96714. if (depthOnlySubMeshes.length) {
  96715. engine.setColorWrite(false);
  96716. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96717. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96718. }
  96719. engine.setColorWrite(true);
  96720. }
  96721. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96722. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96723. }
  96724. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96725. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96726. }
  96727. for (index = 0; index < transparentSubMeshes.length; index++) {
  96728. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96729. }
  96730. };
  96731. this._mainTexture.onClearObservable.add(function (engine) {
  96732. engine.clear(_this.neutralColor, true, true, true);
  96733. });
  96734. };
  96735. /**
  96736. * Checks for the readiness of the element composing the layer.
  96737. * @param subMesh the mesh to check for
  96738. * @param useInstances specify wether or not to use instances to render the mesh
  96739. * @param emissiveTexture the associated emissive texture used to generate the glow
  96740. * @return true if ready otherwise, false
  96741. */
  96742. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96743. var material = subMesh.getMaterial();
  96744. if (!material) {
  96745. return false;
  96746. }
  96747. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96748. return false;
  96749. }
  96750. var defines = [];
  96751. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96752. var mesh = subMesh.getMesh();
  96753. var uv1 = false;
  96754. var uv2 = false;
  96755. // Alpha test
  96756. if (material && material.needAlphaTesting()) {
  96757. var alphaTexture = material.getAlphaTestTexture();
  96758. if (alphaTexture) {
  96759. defines.push("#define ALPHATEST");
  96760. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96761. alphaTexture.coordinatesIndex === 1) {
  96762. defines.push("#define DIFFUSEUV2");
  96763. uv2 = true;
  96764. }
  96765. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96766. defines.push("#define DIFFUSEUV1");
  96767. uv1 = true;
  96768. }
  96769. }
  96770. }
  96771. // Emissive
  96772. if (emissiveTexture) {
  96773. defines.push("#define EMISSIVE");
  96774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96775. emissiveTexture.coordinatesIndex === 1) {
  96776. defines.push("#define EMISSIVEUV2");
  96777. uv2 = true;
  96778. }
  96779. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96780. defines.push("#define EMISSIVEUV1");
  96781. uv1 = true;
  96782. }
  96783. }
  96784. if (uv1) {
  96785. attribs.push(BABYLON.VertexBuffer.UVKind);
  96786. defines.push("#define UV1");
  96787. }
  96788. if (uv2) {
  96789. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96790. defines.push("#define UV2");
  96791. }
  96792. // Bones
  96793. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96796. if (mesh.numBoneInfluencers > 4) {
  96797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96799. }
  96800. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96801. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96802. }
  96803. else {
  96804. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96805. }
  96806. // Morph targets
  96807. var manager = mesh.morphTargetManager;
  96808. var morphInfluencers = 0;
  96809. if (manager) {
  96810. if (manager.numInfluencers > 0) {
  96811. defines.push("#define MORPHTARGETS");
  96812. morphInfluencers = manager.numInfluencers;
  96813. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96814. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96815. }
  96816. }
  96817. // Instances
  96818. if (useInstances) {
  96819. defines.push("#define INSTANCES");
  96820. attribs.push("world0");
  96821. attribs.push("world1");
  96822. attribs.push("world2");
  96823. attribs.push("world3");
  96824. }
  96825. // Get correct effect
  96826. var join = defines.join("\n");
  96827. if (this._cachedDefines !== join) {
  96828. this._cachedDefines = join;
  96829. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96830. }
  96831. return this._effectLayerMapGenerationEffect.isReady();
  96832. };
  96833. /**
  96834. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96835. */
  96836. EffectLayer.prototype.render = function () {
  96837. var currentEffect = this._mergeEffect;
  96838. // Check
  96839. if (!currentEffect.isReady())
  96840. return;
  96841. for (var i = 0; i < this._postProcesses.length; i++) {
  96842. if (!this._postProcesses[i].isReady()) {
  96843. return;
  96844. }
  96845. }
  96846. var engine = this._scene.getEngine();
  96847. this.onBeforeComposeObservable.notifyObservers(this);
  96848. // Render
  96849. engine.enableEffect(currentEffect);
  96850. engine.setState(false);
  96851. // VBOs
  96852. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96853. // Cache
  96854. var previousAlphaMode = engine.getAlphaMode();
  96855. // Go Blend.
  96856. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96857. // Blends the map on the main canvas.
  96858. this._internalRender(currentEffect);
  96859. // Restore Alpha
  96860. engine.setAlphaMode(previousAlphaMode);
  96861. this.onAfterComposeObservable.notifyObservers(this);
  96862. // Handle size changes.
  96863. var size = this._mainTexture.getSize();
  96864. this._setMainTextureSize();
  96865. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96866. // Recreate RTT and post processes on size change.
  96867. this.onSizeChangedObservable.notifyObservers(this);
  96868. this._disposeTextureAndPostProcesses();
  96869. this._createMainTexture();
  96870. this._createTextureAndPostProcesses();
  96871. }
  96872. };
  96873. /**
  96874. * Determine if a given mesh will be used in the current effect.
  96875. * @param mesh mesh to test
  96876. * @returns true if the mesh will be used
  96877. */
  96878. EffectLayer.prototype.hasMesh = function (mesh) {
  96879. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96880. return true;
  96881. }
  96882. return false;
  96883. };
  96884. /**
  96885. * Returns true if the layer contains information to display, otherwise false.
  96886. * @returns true if the glow layer should be rendered
  96887. */
  96888. EffectLayer.prototype.shouldRender = function () {
  96889. return this.isEnabled && this._shouldRender;
  96890. };
  96891. /**
  96892. * Returns true if the mesh should render, otherwise false.
  96893. * @param mesh The mesh to render
  96894. * @returns true if it should render otherwise false
  96895. */
  96896. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96897. return true;
  96898. };
  96899. /**
  96900. * Returns true if the mesh should render, otherwise false.
  96901. * @param mesh The mesh to render
  96902. * @returns true if it should render otherwise false
  96903. */
  96904. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96905. return true;
  96906. };
  96907. /**
  96908. * Renders the submesh passed in parameter to the generation map.
  96909. */
  96910. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96911. var _this = this;
  96912. if (!this.shouldRender()) {
  96913. return;
  96914. }
  96915. var material = subMesh.getMaterial();
  96916. var mesh = subMesh.getRenderingMesh();
  96917. var scene = this._scene;
  96918. var engine = scene.getEngine();
  96919. if (!material) {
  96920. return;
  96921. }
  96922. // Do not block in blend mode.
  96923. if (material.needAlphaBlendingForMesh(mesh)) {
  96924. return;
  96925. }
  96926. // Culling
  96927. engine.setState(material.backFaceCulling);
  96928. // Managing instances
  96929. var batch = mesh._getInstancesRenderList(subMesh._id);
  96930. if (batch.mustReturn) {
  96931. return;
  96932. }
  96933. // Early Exit per mesh
  96934. if (!this._shouldRenderMesh(mesh)) {
  96935. return;
  96936. }
  96937. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96938. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96939. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96940. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96941. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96942. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96943. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96944. // Alpha test
  96945. if (material && material.needAlphaTesting()) {
  96946. var alphaTexture = material.getAlphaTestTexture();
  96947. if (alphaTexture) {
  96948. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96949. var textureMatrix = alphaTexture.getTextureMatrix();
  96950. if (textureMatrix) {
  96951. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96952. }
  96953. }
  96954. }
  96955. // Glow emissive only
  96956. if (this._emissiveTextureAndColor.texture) {
  96957. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96958. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96959. }
  96960. // Bones
  96961. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96962. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96963. }
  96964. // Morph targets
  96965. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96966. // Draw
  96967. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96968. }
  96969. else {
  96970. // Need to reset refresh rate of the main map
  96971. this._mainTexture.resetRefreshCounter();
  96972. }
  96973. };
  96974. /**
  96975. * Rebuild the required buffers.
  96976. * @hidden Internal use only.
  96977. */
  96978. EffectLayer.prototype._rebuild = function () {
  96979. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96980. if (vb) {
  96981. vb._rebuild();
  96982. }
  96983. this._generateIndexBuffer();
  96984. };
  96985. /**
  96986. * Dispose only the render target textures and post process.
  96987. */
  96988. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96989. this._mainTexture.dispose();
  96990. for (var i = 0; i < this._postProcesses.length; i++) {
  96991. if (this._postProcesses[i]) {
  96992. this._postProcesses[i].dispose();
  96993. }
  96994. }
  96995. this._postProcesses = [];
  96996. for (var i = 0; i < this._textures.length; i++) {
  96997. if (this._textures[i]) {
  96998. this._textures[i].dispose();
  96999. }
  97000. }
  97001. this._textures = [];
  97002. };
  97003. /**
  97004. * Dispose the highlight layer and free resources.
  97005. */
  97006. EffectLayer.prototype.dispose = function () {
  97007. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97008. if (vertexBuffer) {
  97009. vertexBuffer.dispose();
  97010. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97011. }
  97012. if (this._indexBuffer) {
  97013. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97014. this._indexBuffer = null;
  97015. }
  97016. // Clean textures and post processes
  97017. this._disposeTextureAndPostProcesses();
  97018. // Remove from scene
  97019. var index = this._scene.effectLayers.indexOf(this, 0);
  97020. if (index > -1) {
  97021. this._scene.effectLayers.splice(index, 1);
  97022. }
  97023. // Callback
  97024. this.onDisposeObservable.notifyObservers(this);
  97025. this.onDisposeObservable.clear();
  97026. this.onBeforeRenderMainTextureObservable.clear();
  97027. this.onBeforeComposeObservable.clear();
  97028. this.onAfterComposeObservable.clear();
  97029. this.onSizeChangedObservable.clear();
  97030. };
  97031. /**
  97032. * Gets the class name of the effect layer
  97033. * @returns the string with the class name of the effect layer
  97034. */
  97035. EffectLayer.prototype.getClassName = function () {
  97036. return "EffectLayer";
  97037. };
  97038. /**
  97039. * Creates an effect layer from parsed effect layer data
  97040. * @param parsedEffectLayer defines effect layer data
  97041. * @param scene defines the current scene
  97042. * @param rootUrl defines the root URL containing the effect layer information
  97043. * @returns a parsed effect Layer
  97044. */
  97045. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97046. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97047. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97048. };
  97049. __decorate([
  97050. BABYLON.serialize()
  97051. ], EffectLayer.prototype, "name", void 0);
  97052. __decorate([
  97053. BABYLON.serializeAsColor4()
  97054. ], EffectLayer.prototype, "neutralColor", void 0);
  97055. __decorate([
  97056. BABYLON.serialize()
  97057. ], EffectLayer.prototype, "isEnabled", void 0);
  97058. __decorate([
  97059. BABYLON.serializeAsCameraReference()
  97060. ], EffectLayer.prototype, "camera", null);
  97061. __decorate([
  97062. BABYLON.serialize()
  97063. ], EffectLayer.prototype, "renderingGroupId", null);
  97064. return EffectLayer;
  97065. }());
  97066. BABYLON.EffectLayer = EffectLayer;
  97067. })(BABYLON || (BABYLON = {}));
  97068. //# sourceMappingURL=babylon.effectLayer.js.map
  97069. var BABYLON;
  97070. (function (BABYLON) {
  97071. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97072. for (var index = 0; index < this.effectLayers.length; index++) {
  97073. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97074. return this.effectLayers[index];
  97075. }
  97076. }
  97077. return null;
  97078. };
  97079. /**
  97080. * Special Glow Blur post process only blurring the alpha channel
  97081. * It enforces keeping the most luminous color in the color channel.
  97082. */
  97083. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97084. __extends(GlowBlurPostProcess, _super);
  97085. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97087. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97088. _this.direction = direction;
  97089. _this.kernel = kernel;
  97090. _this.onApplyObservable.add(function (effect) {
  97091. effect.setFloat2("screenSize", _this.width, _this.height);
  97092. effect.setVector2("direction", _this.direction);
  97093. effect.setFloat("blurWidth", _this.kernel);
  97094. });
  97095. return _this;
  97096. }
  97097. return GlowBlurPostProcess;
  97098. }(BABYLON.PostProcess));
  97099. /**
  97100. * The highlight layer Helps adding a glow effect around a mesh.
  97101. *
  97102. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97103. * glowy meshes to your scene.
  97104. *
  97105. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97106. */
  97107. var HighlightLayer = /** @class */ (function (_super) {
  97108. __extends(HighlightLayer, _super);
  97109. /**
  97110. * Instantiates a new highlight Layer and references it to the scene..
  97111. * @param name The name of the layer
  97112. * @param scene The scene to use the layer in
  97113. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97114. */
  97115. function HighlightLayer(name, scene, options) {
  97116. var _this = _super.call(this, name, scene) || this;
  97117. _this.name = name;
  97118. /**
  97119. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97120. */
  97121. _this.innerGlow = true;
  97122. /**
  97123. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97124. */
  97125. _this.outerGlow = true;
  97126. /**
  97127. * An event triggered when the highlight layer is being blurred.
  97128. */
  97129. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97130. /**
  97131. * An event triggered when the highlight layer has been blurred.
  97132. */
  97133. _this.onAfterBlurObservable = new BABYLON.Observable();
  97134. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97135. _this._meshes = {};
  97136. _this._excludedMeshes = {};
  97137. _this.neutralColor = HighlightLayer.NeutralColor;
  97138. // Warn on stencil
  97139. if (!_this._engine.isStencilEnable) {
  97140. 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 }");
  97141. }
  97142. // Adapt options
  97143. _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);
  97144. // Initialize the layer
  97145. _this._init({
  97146. alphaBlendingMode: _this._options.alphaBlendingMode,
  97147. camera: _this._options.camera,
  97148. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97149. mainTextureRatio: _this._options.mainTextureRatio,
  97150. renderingGroupId: _this._options.renderingGroupId
  97151. });
  97152. // Do not render as long as no meshes have been added
  97153. _this._shouldRender = false;
  97154. return _this;
  97155. }
  97156. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97157. /**
  97158. * Gets the horizontal size of the blur.
  97159. */
  97160. get: function () {
  97161. return this._horizontalBlurPostprocess.kernel;
  97162. },
  97163. /**
  97164. * Specifies the horizontal size of the blur.
  97165. */
  97166. set: function (value) {
  97167. this._horizontalBlurPostprocess.kernel = value;
  97168. },
  97169. enumerable: true,
  97170. configurable: true
  97171. });
  97172. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97173. /**
  97174. * Gets the vertical size of the blur.
  97175. */
  97176. get: function () {
  97177. return this._verticalBlurPostprocess.kernel;
  97178. },
  97179. /**
  97180. * Specifies the vertical size of the blur.
  97181. */
  97182. set: function (value) {
  97183. this._verticalBlurPostprocess.kernel = value;
  97184. },
  97185. enumerable: true,
  97186. configurable: true
  97187. });
  97188. /**
  97189. * Get the effect name of the layer.
  97190. * @return The effect name
  97191. */
  97192. HighlightLayer.prototype.getEffectName = function () {
  97193. return HighlightLayer.EffectName;
  97194. };
  97195. /**
  97196. * Create the merge effect. This is the shader use to blit the information back
  97197. * to the main canvas at the end of the scene rendering.
  97198. */
  97199. HighlightLayer.prototype._createMergeEffect = function () {
  97200. // Effect
  97201. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97202. };
  97203. /**
  97204. * Creates the render target textures and post processes used in the highlight layer.
  97205. */
  97206. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97207. var _this = this;
  97208. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97209. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97210. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97211. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97212. var textureType = 0;
  97213. if (this._engine.getCaps().textureHalfFloatRender) {
  97214. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97215. }
  97216. else {
  97217. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97218. }
  97219. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97220. width: blurTextureWidth,
  97221. height: blurTextureHeight
  97222. }, this._scene, false, true, textureType);
  97223. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97224. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97225. this._blurTexture.anisotropicFilteringLevel = 16;
  97226. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97227. this._blurTexture.renderParticles = false;
  97228. this._blurTexture.ignoreCameraViewport = true;
  97229. this._textures = [this._blurTexture];
  97230. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97231. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97232. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97233. effect.setTexture("textureSampler", _this._mainTexture);
  97234. });
  97235. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97236. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97237. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97238. });
  97239. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97240. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97241. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97242. });
  97243. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97244. }
  97245. else {
  97246. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97247. width: blurTextureWidth,
  97248. height: blurTextureHeight
  97249. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97250. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97251. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97252. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97253. effect.setTexture("textureSampler", _this._mainTexture);
  97254. });
  97255. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97256. width: blurTextureWidth,
  97257. height: blurTextureHeight
  97258. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97259. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97260. }
  97261. this._mainTexture.onAfterUnbindObservable.add(function () {
  97262. _this.onBeforeBlurObservable.notifyObservers(_this);
  97263. var internalTexture = _this._blurTexture.getInternalTexture();
  97264. if (internalTexture) {
  97265. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97266. }
  97267. _this.onAfterBlurObservable.notifyObservers(_this);
  97268. });
  97269. // Prevent autoClear.
  97270. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97271. };
  97272. /**
  97273. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97274. */
  97275. HighlightLayer.prototype.needStencil = function () {
  97276. return true;
  97277. };
  97278. /**
  97279. * Checks for the readiness of the element composing the layer.
  97280. * @param subMesh the mesh to check for
  97281. * @param useInstances specify wether or not to use instances to render the mesh
  97282. * @param emissiveTexture the associated emissive texture used to generate the glow
  97283. * @return true if ready otherwise, false
  97284. */
  97285. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97286. var material = subMesh.getMaterial();
  97287. var mesh = subMesh.getRenderingMesh();
  97288. if (!material || !mesh || !this._meshes) {
  97289. return false;
  97290. }
  97291. var emissiveTexture = null;
  97292. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97293. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97294. emissiveTexture = material.emissiveTexture;
  97295. }
  97296. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97297. };
  97298. /**
  97299. * Implementation specific of rendering the generating effect on the main canvas.
  97300. * @param effect The effect used to render through
  97301. */
  97302. HighlightLayer.prototype._internalRender = function (effect) {
  97303. // Texture
  97304. effect.setTexture("textureSampler", this._blurTexture);
  97305. // Cache
  97306. var engine = this._engine;
  97307. var previousStencilBuffer = engine.getStencilBuffer();
  97308. var previousStencilFunction = engine.getStencilFunction();
  97309. var previousStencilMask = engine.getStencilMask();
  97310. var previousStencilOperationPass = engine.getStencilOperationPass();
  97311. var previousStencilOperationFail = engine.getStencilOperationFail();
  97312. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97313. var previousStencilReference = engine.getStencilFunctionReference();
  97314. // Stencil operations
  97315. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97316. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97317. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97318. // Draw order
  97319. engine.setStencilMask(0x00);
  97320. engine.setStencilBuffer(true);
  97321. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97322. // 2 passes inner outer
  97323. if (this.outerGlow) {
  97324. effect.setFloat("offset", 0);
  97325. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97326. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97327. }
  97328. if (this.innerGlow) {
  97329. effect.setFloat("offset", 1);
  97330. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97332. }
  97333. // Restore Cache
  97334. engine.setStencilFunction(previousStencilFunction);
  97335. engine.setStencilMask(previousStencilMask);
  97336. engine.setStencilBuffer(previousStencilBuffer);
  97337. engine.setStencilOperationPass(previousStencilOperationPass);
  97338. engine.setStencilOperationFail(previousStencilOperationFail);
  97339. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97340. engine.setStencilFunctionReference(previousStencilReference);
  97341. };
  97342. /**
  97343. * Returns true if the layer contains information to display, otherwise false.
  97344. */
  97345. HighlightLayer.prototype.shouldRender = function () {
  97346. if (_super.prototype.shouldRender.call(this)) {
  97347. return this._meshes ? true : false;
  97348. }
  97349. return false;
  97350. };
  97351. /**
  97352. * Returns true if the mesh should render, otherwise false.
  97353. * @param mesh The mesh to render
  97354. * @returns true if it should render otherwise false
  97355. */
  97356. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97357. // Excluded Mesh
  97358. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97359. return false;
  97360. }
  97361. ;
  97362. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97363. return false;
  97364. }
  97365. return true;
  97366. };
  97367. /**
  97368. * Sets the required values for both the emissive texture and and the main color.
  97369. */
  97370. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97371. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97372. if (highlightLayerMesh) {
  97373. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97374. }
  97375. else {
  97376. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97377. }
  97378. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97379. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97380. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97381. }
  97382. else {
  97383. this._emissiveTextureAndColor.texture = null;
  97384. }
  97385. };
  97386. /**
  97387. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97388. * @param mesh The mesh to exclude from the highlight layer
  97389. */
  97390. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97391. if (!this._excludedMeshes) {
  97392. return;
  97393. }
  97394. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97395. if (!meshExcluded) {
  97396. this._excludedMeshes[mesh.uniqueId] = {
  97397. mesh: mesh,
  97398. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97399. mesh.getEngine().setStencilBuffer(false);
  97400. }),
  97401. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97402. mesh.getEngine().setStencilBuffer(true);
  97403. }),
  97404. };
  97405. }
  97406. };
  97407. /**
  97408. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97409. * @param mesh The mesh to highlight
  97410. */
  97411. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97412. if (!this._excludedMeshes) {
  97413. return;
  97414. }
  97415. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97416. if (meshExcluded) {
  97417. if (meshExcluded.beforeRender) {
  97418. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97419. }
  97420. if (meshExcluded.afterRender) {
  97421. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97422. }
  97423. }
  97424. this._excludedMeshes[mesh.uniqueId] = null;
  97425. };
  97426. /**
  97427. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97428. * @param mesh mesh to test
  97429. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97430. */
  97431. HighlightLayer.prototype.hasMesh = function (mesh) {
  97432. if (!this._meshes) {
  97433. return false;
  97434. }
  97435. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97436. return false;
  97437. }
  97438. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97439. };
  97440. /**
  97441. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97442. * @param mesh The mesh to highlight
  97443. * @param color The color of the highlight
  97444. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97445. */
  97446. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97447. var _this = this;
  97448. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97449. if (!this._meshes) {
  97450. return;
  97451. }
  97452. var meshHighlight = this._meshes[mesh.uniqueId];
  97453. if (meshHighlight) {
  97454. meshHighlight.color = color;
  97455. }
  97456. else {
  97457. this._meshes[mesh.uniqueId] = {
  97458. mesh: mesh,
  97459. color: color,
  97460. // Lambda required for capture due to Observable this context
  97461. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97462. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97463. _this._defaultStencilReference(mesh);
  97464. }
  97465. else {
  97466. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97467. }
  97468. }),
  97469. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97470. glowEmissiveOnly: glowEmissiveOnly
  97471. };
  97472. mesh.onDisposeObservable.add(function () {
  97473. _this._disposeMesh(mesh);
  97474. });
  97475. }
  97476. this._shouldRender = true;
  97477. };
  97478. /**
  97479. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97480. * @param mesh The mesh to highlight
  97481. */
  97482. HighlightLayer.prototype.removeMesh = function (mesh) {
  97483. if (!this._meshes) {
  97484. return;
  97485. }
  97486. var meshHighlight = this._meshes[mesh.uniqueId];
  97487. if (meshHighlight) {
  97488. if (meshHighlight.observerHighlight) {
  97489. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97490. }
  97491. if (meshHighlight.observerDefault) {
  97492. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97493. }
  97494. delete this._meshes[mesh.uniqueId];
  97495. }
  97496. this._shouldRender = false;
  97497. for (var meshHighlightToCheck in this._meshes) {
  97498. if (this._meshes[meshHighlightToCheck]) {
  97499. this._shouldRender = true;
  97500. break;
  97501. }
  97502. }
  97503. };
  97504. /**
  97505. * Force the stencil to the normal expected value for none glowing parts
  97506. */
  97507. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97508. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97509. };
  97510. /**
  97511. * Free any resources and references associated to a mesh.
  97512. * Internal use
  97513. * @param mesh The mesh to free.
  97514. */
  97515. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97516. this.removeMesh(mesh);
  97517. this.removeExcludedMesh(mesh);
  97518. };
  97519. /**
  97520. * Dispose the highlight layer and free resources.
  97521. */
  97522. HighlightLayer.prototype.dispose = function () {
  97523. if (this._meshes) {
  97524. // Clean mesh references
  97525. for (var id in this._meshes) {
  97526. var meshHighlight = this._meshes[id];
  97527. if (meshHighlight && meshHighlight.mesh) {
  97528. if (meshHighlight.observerHighlight) {
  97529. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97530. }
  97531. if (meshHighlight.observerDefault) {
  97532. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97533. }
  97534. }
  97535. }
  97536. this._meshes = null;
  97537. }
  97538. if (this._excludedMeshes) {
  97539. for (var id in this._excludedMeshes) {
  97540. var meshHighlight = this._excludedMeshes[id];
  97541. if (meshHighlight) {
  97542. if (meshHighlight.beforeRender) {
  97543. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97544. }
  97545. if (meshHighlight.afterRender) {
  97546. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97547. }
  97548. }
  97549. }
  97550. this._excludedMeshes = null;
  97551. }
  97552. _super.prototype.dispose.call(this);
  97553. };
  97554. /**
  97555. * Gets the class name of the effect layer
  97556. * @returns the string with the class name of the effect layer
  97557. */
  97558. HighlightLayer.prototype.getClassName = function () {
  97559. return "HighlightLayer";
  97560. };
  97561. /**
  97562. * Serializes this Highlight layer
  97563. * @returns a serialized Highlight layer object
  97564. */
  97565. HighlightLayer.prototype.serialize = function () {
  97566. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97567. serializationObject.customType = "BABYLON.HighlightLayer";
  97568. // Highlighted meshes
  97569. serializationObject.meshes = [];
  97570. if (this._meshes) {
  97571. for (var m in this._meshes) {
  97572. var mesh = this._meshes[m];
  97573. if (mesh) {
  97574. serializationObject.meshes.push({
  97575. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97576. color: mesh.color.asArray(),
  97577. meshId: mesh.mesh.id
  97578. });
  97579. }
  97580. }
  97581. }
  97582. // Excluded meshes
  97583. serializationObject.excludedMeshes = [];
  97584. if (this._excludedMeshes) {
  97585. for (var e in this._excludedMeshes) {
  97586. var excludedMesh = this._excludedMeshes[e];
  97587. if (excludedMesh) {
  97588. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97589. }
  97590. }
  97591. }
  97592. return serializationObject;
  97593. };
  97594. /**
  97595. * Creates a Highlight layer from parsed Highlight layer data
  97596. * @param parsedHightlightLayer defines the Highlight layer data
  97597. * @param scene defines the current scene
  97598. * @param rootUrl defines the root URL containing the Highlight layer information
  97599. * @returns a parsed Highlight layer
  97600. */
  97601. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97602. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97603. var index;
  97604. // Excluded meshes
  97605. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97606. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97607. if (mesh) {
  97608. hl.addExcludedMesh(mesh);
  97609. }
  97610. }
  97611. // Included meshes
  97612. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97613. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97614. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97615. if (mesh) {
  97616. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97617. }
  97618. }
  97619. return hl;
  97620. };
  97621. /**
  97622. * Effect Name of the highlight layer.
  97623. */
  97624. HighlightLayer.EffectName = "HighlightLayer";
  97625. /**
  97626. * The neutral color used during the preparation of the glow effect.
  97627. * This is black by default as the blend operation is a blend operation.
  97628. */
  97629. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97630. /**
  97631. * Stencil value used for glowing meshes.
  97632. */
  97633. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97634. /**
  97635. * Stencil value used for the other meshes in the scene.
  97636. */
  97637. HighlightLayer.NormalMeshStencilReference = 0x01;
  97638. __decorate([
  97639. BABYLON.serialize()
  97640. ], HighlightLayer.prototype, "innerGlow", void 0);
  97641. __decorate([
  97642. BABYLON.serialize()
  97643. ], HighlightLayer.prototype, "outerGlow", void 0);
  97644. __decorate([
  97645. BABYLON.serialize()
  97646. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97647. __decorate([
  97648. BABYLON.serialize()
  97649. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97650. __decorate([
  97651. BABYLON.serialize("options")
  97652. ], HighlightLayer.prototype, "_options", void 0);
  97653. return HighlightLayer;
  97654. }(BABYLON.EffectLayer));
  97655. BABYLON.HighlightLayer = HighlightLayer;
  97656. })(BABYLON || (BABYLON = {}));
  97657. //# sourceMappingURL=babylon.highlightLayer.js.map
  97658. var BABYLON;
  97659. (function (BABYLON) {
  97660. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97661. for (var index = 0; index < this.effectLayers.length; index++) {
  97662. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97663. return this.effectLayers[index];
  97664. }
  97665. }
  97666. return null;
  97667. };
  97668. /**
  97669. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97670. *
  97671. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97672. * glowy meshes to your scene.
  97673. *
  97674. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97675. */
  97676. var GlowLayer = /** @class */ (function (_super) {
  97677. __extends(GlowLayer, _super);
  97678. /**
  97679. * Instantiates a new glow Layer and references it to the scene.
  97680. * @param name The name of the layer
  97681. * @param scene The scene to use the layer in
  97682. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97683. */
  97684. function GlowLayer(name, scene, options) {
  97685. var _this = _super.call(this, name, scene) || this;
  97686. _this._intensity = 1.0;
  97687. _this._includedOnlyMeshes = [];
  97688. _this._excludedMeshes = [];
  97689. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97690. // Adapt options
  97691. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97692. // Initialize the layer
  97693. _this._init({
  97694. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97695. camera: _this._options.camera,
  97696. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97697. mainTextureRatio: _this._options.mainTextureRatio,
  97698. renderingGroupId: _this._options.renderingGroupId
  97699. });
  97700. return _this;
  97701. }
  97702. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97703. /**
  97704. * Gets the kernel size of the blur.
  97705. */
  97706. get: function () {
  97707. return this._horizontalBlurPostprocess1.kernel;
  97708. },
  97709. /**
  97710. * Sets the kernel size of the blur.
  97711. */
  97712. set: function (value) {
  97713. this._horizontalBlurPostprocess1.kernel = value;
  97714. this._verticalBlurPostprocess1.kernel = value;
  97715. this._horizontalBlurPostprocess2.kernel = value;
  97716. this._verticalBlurPostprocess2.kernel = value;
  97717. },
  97718. enumerable: true,
  97719. configurable: true
  97720. });
  97721. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97722. /**
  97723. * Gets the glow intensity.
  97724. */
  97725. get: function () {
  97726. return this._intensity;
  97727. },
  97728. /**
  97729. * Sets the glow intensity.
  97730. */
  97731. set: function (value) {
  97732. this._intensity = value;
  97733. },
  97734. enumerable: true,
  97735. configurable: true
  97736. });
  97737. /**
  97738. * Get the effect name of the layer.
  97739. * @return The effect name
  97740. */
  97741. GlowLayer.prototype.getEffectName = function () {
  97742. return GlowLayer.EffectName;
  97743. };
  97744. /**
  97745. * Create the merge effect. This is the shader use to blit the information back
  97746. * to the main canvas at the end of the scene rendering.
  97747. */
  97748. GlowLayer.prototype._createMergeEffect = function () {
  97749. // Effect
  97750. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97751. };
  97752. /**
  97753. * Creates the render target textures and post processes used in the glow layer.
  97754. */
  97755. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97756. var _this = this;
  97757. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97758. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97759. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97760. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97761. var textureType = 0;
  97762. if (this._engine.getCaps().textureHalfFloatRender) {
  97763. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97764. }
  97765. else {
  97766. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97767. }
  97768. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97769. width: blurTextureWidth,
  97770. height: blurTextureHeight
  97771. }, this._scene, false, true, textureType);
  97772. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97773. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97774. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97775. this._blurTexture1.renderParticles = false;
  97776. this._blurTexture1.ignoreCameraViewport = true;
  97777. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97778. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97779. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97780. width: blurTextureWidth2,
  97781. height: blurTextureHeight2
  97782. }, this._scene, false, true, textureType);
  97783. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97784. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97785. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97786. this._blurTexture2.renderParticles = false;
  97787. this._blurTexture2.ignoreCameraViewport = true;
  97788. this._textures = [this._blurTexture1, this._blurTexture2];
  97789. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97790. width: blurTextureWidth,
  97791. height: blurTextureHeight
  97792. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97793. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97794. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97795. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97796. effect.setTexture("textureSampler", _this._mainTexture);
  97797. });
  97798. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97799. width: blurTextureWidth,
  97800. height: blurTextureHeight
  97801. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97802. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97803. width: blurTextureWidth2,
  97804. height: blurTextureHeight2
  97805. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97806. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97807. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97808. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97809. effect.setTexture("textureSampler", _this._blurTexture1);
  97810. });
  97811. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97812. width: blurTextureWidth2,
  97813. height: blurTextureHeight2
  97814. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97815. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97816. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97817. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97818. this._mainTexture.samples = this._options.mainTextureSamples;
  97819. this._mainTexture.onAfterUnbindObservable.add(function () {
  97820. var internalTexture = _this._blurTexture1.getInternalTexture();
  97821. if (internalTexture) {
  97822. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97823. internalTexture = _this._blurTexture2.getInternalTexture();
  97824. if (internalTexture) {
  97825. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97826. }
  97827. }
  97828. });
  97829. // Prevent autoClear.
  97830. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97831. };
  97832. /**
  97833. * Checks for the readiness of the element composing the layer.
  97834. * @param subMesh the mesh to check for
  97835. * @param useInstances specify wether or not to use instances to render the mesh
  97836. * @param emissiveTexture the associated emissive texture used to generate the glow
  97837. * @return true if ready otherwise, false
  97838. */
  97839. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97840. var material = subMesh.getMaterial();
  97841. var mesh = subMesh.getRenderingMesh();
  97842. if (!material || !mesh) {
  97843. return false;
  97844. }
  97845. var emissiveTexture = material.emissiveTexture;
  97846. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97847. };
  97848. /**
  97849. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97850. */
  97851. GlowLayer.prototype.needStencil = function () {
  97852. return false;
  97853. };
  97854. /**
  97855. * Implementation specific of rendering the generating effect on the main canvas.
  97856. * @param effect The effect used to render through
  97857. */
  97858. GlowLayer.prototype._internalRender = function (effect) {
  97859. // Texture
  97860. effect.setTexture("textureSampler", this._blurTexture1);
  97861. effect.setTexture("textureSampler2", this._blurTexture2);
  97862. effect.setFloat("offset", this._intensity);
  97863. // Cache
  97864. var engine = this._engine;
  97865. var previousStencilBuffer = engine.getStencilBuffer();
  97866. // Draw order
  97867. engine.setStencilBuffer(false);
  97868. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97869. // Draw order
  97870. engine.setStencilBuffer(previousStencilBuffer);
  97871. };
  97872. /**
  97873. * Sets the required values for both the emissive texture and and the main color.
  97874. */
  97875. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97876. var textureLevel = 1.0;
  97877. if (this.customEmissiveTextureSelector) {
  97878. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97879. }
  97880. else {
  97881. if (material) {
  97882. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97883. if (this._emissiveTextureAndColor.texture) {
  97884. textureLevel = this._emissiveTextureAndColor.texture.level;
  97885. }
  97886. }
  97887. else {
  97888. this._emissiveTextureAndColor.texture = null;
  97889. }
  97890. }
  97891. if (this.customEmissiveColorSelector) {
  97892. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97893. }
  97894. else {
  97895. if (material.emissiveColor) {
  97896. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97897. }
  97898. else {
  97899. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97900. }
  97901. }
  97902. };
  97903. /**
  97904. * Returns true if the mesh should render, otherwise false.
  97905. * @param mesh The mesh to render
  97906. * @returns true if it should render otherwise false
  97907. */
  97908. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97909. return this.hasMesh(mesh);
  97910. };
  97911. /**
  97912. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97913. * @param mesh The mesh to exclude from the glow layer
  97914. */
  97915. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97916. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97917. this._excludedMeshes.push(mesh.uniqueId);
  97918. }
  97919. };
  97920. /**
  97921. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97922. * @param mesh The mesh to remove
  97923. */
  97924. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97925. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97926. if (index !== -1) {
  97927. this._excludedMeshes.splice(index, 1);
  97928. }
  97929. };
  97930. /**
  97931. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97932. * @param mesh The mesh to include in the glow layer
  97933. */
  97934. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97935. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97936. this._includedOnlyMeshes.push(mesh.uniqueId);
  97937. }
  97938. };
  97939. /**
  97940. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97941. * @param mesh The mesh to remove
  97942. */
  97943. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97944. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97945. if (index !== -1) {
  97946. this._includedOnlyMeshes.splice(index, 1);
  97947. }
  97948. };
  97949. /**
  97950. * Determine if a given mesh will be used in the glow layer
  97951. * @param mesh The mesh to test
  97952. * @returns true if the mesh will be highlighted by the current glow layer
  97953. */
  97954. GlowLayer.prototype.hasMesh = function (mesh) {
  97955. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97956. return false;
  97957. }
  97958. // Included Mesh
  97959. if (this._includedOnlyMeshes.length) {
  97960. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97961. }
  97962. ;
  97963. // Excluded Mesh
  97964. if (this._excludedMeshes.length) {
  97965. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97966. }
  97967. ;
  97968. return true;
  97969. };
  97970. /**
  97971. * Free any resources and references associated to a mesh.
  97972. * Internal use
  97973. * @param mesh The mesh to free.
  97974. */
  97975. GlowLayer.prototype._disposeMesh = function (mesh) {
  97976. this.removeIncludedOnlyMesh(mesh);
  97977. this.removeExcludedMesh(mesh);
  97978. };
  97979. /**
  97980. * Gets the class name of the effect layer
  97981. * @returns the string with the class name of the effect layer
  97982. */
  97983. GlowLayer.prototype.getClassName = function () {
  97984. return "GlowLayer";
  97985. };
  97986. /**
  97987. * Serializes this glow layer
  97988. * @returns a serialized glow layer object
  97989. */
  97990. GlowLayer.prototype.serialize = function () {
  97991. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97992. serializationObject.customType = "BABYLON.GlowLayer";
  97993. var index;
  97994. // Included meshes
  97995. serializationObject.includedMeshes = [];
  97996. if (this._includedOnlyMeshes.length) {
  97997. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97998. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97999. if (mesh) {
  98000. serializationObject.includedMeshes.push(mesh.id);
  98001. }
  98002. }
  98003. }
  98004. // Excluded meshes
  98005. serializationObject.excludedMeshes = [];
  98006. if (this._excludedMeshes.length) {
  98007. for (index = 0; index < this._excludedMeshes.length; index++) {
  98008. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98009. if (mesh) {
  98010. serializationObject.excludedMeshes.push(mesh.id);
  98011. }
  98012. }
  98013. }
  98014. return serializationObject;
  98015. };
  98016. /**
  98017. * Creates a Glow Layer from parsed glow layer data
  98018. * @param parsedGlowLayer defines glow layer data
  98019. * @param scene defines the current scene
  98020. * @param rootUrl defines the root URL containing the glow layer information
  98021. * @returns a parsed Glow Layer
  98022. */
  98023. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98024. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98025. var index;
  98026. // Excluded meshes
  98027. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98028. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98029. if (mesh) {
  98030. gl.addExcludedMesh(mesh);
  98031. }
  98032. }
  98033. // Included meshes
  98034. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98035. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98036. if (mesh) {
  98037. gl.addIncludedOnlyMesh(mesh);
  98038. }
  98039. }
  98040. return gl;
  98041. };
  98042. /**
  98043. * Effect Name of the layer.
  98044. */
  98045. GlowLayer.EffectName = "GlowLayer";
  98046. /**
  98047. * The default blur kernel size used for the glow.
  98048. */
  98049. GlowLayer.DefaultBlurKernelSize = 32;
  98050. /**
  98051. * The default texture size ratio used for the glow.
  98052. */
  98053. GlowLayer.DefaultTextureRatio = 0.5;
  98054. __decorate([
  98055. BABYLON.serialize()
  98056. ], GlowLayer.prototype, "blurKernelSize", null);
  98057. __decorate([
  98058. BABYLON.serialize()
  98059. ], GlowLayer.prototype, "intensity", null);
  98060. __decorate([
  98061. BABYLON.serialize("options")
  98062. ], GlowLayer.prototype, "_options", void 0);
  98063. return GlowLayer;
  98064. }(BABYLON.EffectLayer));
  98065. BABYLON.GlowLayer = GlowLayer;
  98066. })(BABYLON || (BABYLON = {}));
  98067. //# sourceMappingURL=babylon.glowLayer.js.map
  98068. var BABYLON;
  98069. (function (BABYLON) {
  98070. /**
  98071. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98072. */
  98073. var AssetTaskState;
  98074. (function (AssetTaskState) {
  98075. /**
  98076. * Initialization
  98077. */
  98078. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98079. /**
  98080. * Running
  98081. */
  98082. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98083. /**
  98084. * Done
  98085. */
  98086. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98087. /**
  98088. * Error
  98089. */
  98090. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98091. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98092. /**
  98093. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98094. */
  98095. var AbstractAssetTask = /** @class */ (function () {
  98096. /**
  98097. * Creates a new {BABYLON.AssetsManager}
  98098. * @param name defines the name of the task
  98099. */
  98100. function AbstractAssetTask(
  98101. /**
  98102. * Task name
  98103. */ name) {
  98104. this.name = name;
  98105. this._isCompleted = false;
  98106. this._taskState = AssetTaskState.INIT;
  98107. }
  98108. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98109. /**
  98110. * Get if the task is completed
  98111. */
  98112. get: function () {
  98113. return this._isCompleted;
  98114. },
  98115. enumerable: true,
  98116. configurable: true
  98117. });
  98118. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98119. /**
  98120. * Gets the current state of the task
  98121. */
  98122. get: function () {
  98123. return this._taskState;
  98124. },
  98125. enumerable: true,
  98126. configurable: true
  98127. });
  98128. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98129. /**
  98130. * Gets the current error object (if task is in error)
  98131. */
  98132. get: function () {
  98133. return this._errorObject;
  98134. },
  98135. enumerable: true,
  98136. configurable: true
  98137. });
  98138. /**
  98139. * Internal only
  98140. * @hidden
  98141. */
  98142. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98143. if (this._errorObject) {
  98144. return;
  98145. }
  98146. this._errorObject = {
  98147. message: message,
  98148. exception: exception
  98149. };
  98150. };
  98151. /**
  98152. * Execute the current task
  98153. * @param scene defines the scene where you want your assets to be loaded
  98154. * @param onSuccess is a callback called when the task is successfully executed
  98155. * @param onError is a callback called if an error occurs
  98156. */
  98157. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98158. var _this = this;
  98159. this._taskState = AssetTaskState.RUNNING;
  98160. this.runTask(scene, function () {
  98161. _this.onDoneCallback(onSuccess, onError);
  98162. }, function (msg, exception) {
  98163. _this.onErrorCallback(onError, msg, exception);
  98164. });
  98165. };
  98166. /**
  98167. * Execute the current task
  98168. * @param scene defines the scene where you want your assets to be loaded
  98169. * @param onSuccess is a callback called when the task is successfully executed
  98170. * @param onError is a callback called if an error occurs
  98171. */
  98172. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98173. throw new Error("runTask is not implemented");
  98174. };
  98175. /**
  98176. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98177. * This can be used with failed tasks that have the reason for failure fixed.
  98178. */
  98179. AbstractAssetTask.prototype.reset = function () {
  98180. this._taskState = AssetTaskState.INIT;
  98181. };
  98182. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98183. this._taskState = AssetTaskState.ERROR;
  98184. this._errorObject = {
  98185. message: message,
  98186. exception: exception
  98187. };
  98188. if (this.onError) {
  98189. this.onError(this, message, exception);
  98190. }
  98191. onError();
  98192. };
  98193. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98194. try {
  98195. this._taskState = AssetTaskState.DONE;
  98196. this._isCompleted = true;
  98197. if (this.onSuccess) {
  98198. this.onSuccess(this);
  98199. }
  98200. onSuccess();
  98201. }
  98202. catch (e) {
  98203. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98204. }
  98205. };
  98206. return AbstractAssetTask;
  98207. }());
  98208. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98209. /**
  98210. * Class used to share progress information about assets loading
  98211. */
  98212. var AssetsProgressEvent = /** @class */ (function () {
  98213. /**
  98214. * Creates a {BABYLON.AssetsProgressEvent}
  98215. * @param remainingCount defines the number of remaining tasks to process
  98216. * @param totalCount defines the total number of tasks
  98217. * @param task defines the task that was just processed
  98218. */
  98219. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98220. this.remainingCount = remainingCount;
  98221. this.totalCount = totalCount;
  98222. this.task = task;
  98223. }
  98224. return AssetsProgressEvent;
  98225. }());
  98226. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98227. /**
  98228. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98229. */
  98230. var MeshAssetTask = /** @class */ (function (_super) {
  98231. __extends(MeshAssetTask, _super);
  98232. /**
  98233. * Creates a new {BABYLON.MeshAssetTask}
  98234. * @param name defines the name of the task
  98235. * @param meshesNames defines the list of mesh's names you want to load
  98236. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98237. * @param sceneFilename defines the filename of the scene to load from
  98238. */
  98239. function MeshAssetTask(
  98240. /**
  98241. * Defines the name of the task
  98242. */
  98243. name,
  98244. /**
  98245. * Defines the list of mesh's names you want to load
  98246. */
  98247. meshesNames,
  98248. /**
  98249. * Defines the root url to use as a base to load your meshes and associated resources
  98250. */
  98251. rootUrl,
  98252. /**
  98253. * Defines the filename of the scene to load from
  98254. */
  98255. sceneFilename) {
  98256. var _this = _super.call(this, name) || this;
  98257. _this.name = name;
  98258. _this.meshesNames = meshesNames;
  98259. _this.rootUrl = rootUrl;
  98260. _this.sceneFilename = sceneFilename;
  98261. return _this;
  98262. }
  98263. /**
  98264. * Execute the current task
  98265. * @param scene defines the scene where you want your assets to be loaded
  98266. * @param onSuccess is a callback called when the task is successfully executed
  98267. * @param onError is a callback called if an error occurs
  98268. */
  98269. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98270. var _this = this;
  98271. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98272. _this.loadedMeshes = meshes;
  98273. _this.loadedParticleSystems = particleSystems;
  98274. _this.loadedSkeletons = skeletons;
  98275. onSuccess();
  98276. }, null, function (scene, message, exception) {
  98277. onError(message, exception);
  98278. });
  98279. };
  98280. return MeshAssetTask;
  98281. }(AbstractAssetTask));
  98282. BABYLON.MeshAssetTask = MeshAssetTask;
  98283. /**
  98284. * Define a task used by {BABYLON.AssetsManager} to load text content
  98285. */
  98286. var TextFileAssetTask = /** @class */ (function (_super) {
  98287. __extends(TextFileAssetTask, _super);
  98288. /**
  98289. * Creates a new TextFileAssetTask object
  98290. * @param name defines the name of the task
  98291. * @param url defines the location of the file to load
  98292. */
  98293. function TextFileAssetTask(
  98294. /**
  98295. * Defines the name of the task
  98296. */
  98297. name,
  98298. /**
  98299. * Defines the location of the file to load
  98300. */
  98301. url) {
  98302. var _this = _super.call(this, name) || this;
  98303. _this.name = name;
  98304. _this.url = url;
  98305. return _this;
  98306. }
  98307. /**
  98308. * Execute the current task
  98309. * @param scene defines the scene where you want your assets to be loaded
  98310. * @param onSuccess is a callback called when the task is successfully executed
  98311. * @param onError is a callback called if an error occurs
  98312. */
  98313. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98314. var _this = this;
  98315. scene._loadFile(this.url, function (data) {
  98316. _this.text = data;
  98317. onSuccess();
  98318. }, undefined, false, false, function (request, exception) {
  98319. if (request) {
  98320. onError(request.status + " " + request.statusText, exception);
  98321. }
  98322. });
  98323. };
  98324. return TextFileAssetTask;
  98325. }(AbstractAssetTask));
  98326. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98327. /**
  98328. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98329. */
  98330. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98331. __extends(BinaryFileAssetTask, _super);
  98332. /**
  98333. * Creates a new BinaryFileAssetTask object
  98334. * @param name defines the name of the new task
  98335. * @param url defines the location of the file to load
  98336. */
  98337. function BinaryFileAssetTask(
  98338. /**
  98339. * Defines the name of the task
  98340. */
  98341. name,
  98342. /**
  98343. * Defines the location of the file to load
  98344. */
  98345. url) {
  98346. var _this = _super.call(this, name) || this;
  98347. _this.name = name;
  98348. _this.url = url;
  98349. return _this;
  98350. }
  98351. /**
  98352. * Execute the current task
  98353. * @param scene defines the scene where you want your assets to be loaded
  98354. * @param onSuccess is a callback called when the task is successfully executed
  98355. * @param onError is a callback called if an error occurs
  98356. */
  98357. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98358. var _this = this;
  98359. scene._loadFile(this.url, function (data) {
  98360. _this.data = data;
  98361. onSuccess();
  98362. }, undefined, true, true, function (request, exception) {
  98363. if (request) {
  98364. onError(request.status + " " + request.statusText, exception);
  98365. }
  98366. });
  98367. };
  98368. return BinaryFileAssetTask;
  98369. }(AbstractAssetTask));
  98370. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98371. /**
  98372. * Define a task used by {BABYLON.AssetsManager} to load images
  98373. */
  98374. var ImageAssetTask = /** @class */ (function (_super) {
  98375. __extends(ImageAssetTask, _super);
  98376. /**
  98377. * Creates a new ImageAssetTask
  98378. * @param name defines the name of the task
  98379. * @param url defines the location of the image to load
  98380. */
  98381. function ImageAssetTask(
  98382. /**
  98383. * Defines the name of the task
  98384. */
  98385. name,
  98386. /**
  98387. * Defines the location of the image to load
  98388. */
  98389. url) {
  98390. var _this = _super.call(this, name) || this;
  98391. _this.name = name;
  98392. _this.url = url;
  98393. return _this;
  98394. }
  98395. /**
  98396. * Execute the current task
  98397. * @param scene defines the scene where you want your assets to be loaded
  98398. * @param onSuccess is a callback called when the task is successfully executed
  98399. * @param onError is a callback called if an error occurs
  98400. */
  98401. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98402. var _this = this;
  98403. var img = new Image();
  98404. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98405. img.onload = function () {
  98406. _this.image = img;
  98407. onSuccess();
  98408. };
  98409. img.onerror = function (err) {
  98410. onError("Error loading image", err);
  98411. };
  98412. img.src = this.url;
  98413. };
  98414. return ImageAssetTask;
  98415. }(AbstractAssetTask));
  98416. BABYLON.ImageAssetTask = ImageAssetTask;
  98417. /**
  98418. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98419. */
  98420. var TextureAssetTask = /** @class */ (function (_super) {
  98421. __extends(TextureAssetTask, _super);
  98422. /**
  98423. * Creates a new TextureAssetTask object
  98424. * @param name defines the name of the task
  98425. * @param url defines the location of the file to load
  98426. * @param noMipmap defines if mipmap should not be generated (default is false)
  98427. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98428. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98429. */
  98430. function TextureAssetTask(
  98431. /**
  98432. * Defines the name of the task
  98433. */
  98434. name,
  98435. /**
  98436. * Defines the location of the file to load
  98437. */
  98438. url,
  98439. /**
  98440. * Defines if mipmap should not be generated (default is false)
  98441. */
  98442. noMipmap,
  98443. /**
  98444. * Defines if texture must be inverted on Y axis (default is false)
  98445. */
  98446. invertY,
  98447. /**
  98448. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98449. */
  98450. samplingMode) {
  98451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98452. var _this = _super.call(this, name) || this;
  98453. _this.name = name;
  98454. _this.url = url;
  98455. _this.noMipmap = noMipmap;
  98456. _this.invertY = invertY;
  98457. _this.samplingMode = samplingMode;
  98458. return _this;
  98459. }
  98460. /**
  98461. * Execute the current task
  98462. * @param scene defines the scene where you want your assets to be loaded
  98463. * @param onSuccess is a callback called when the task is successfully executed
  98464. * @param onError is a callback called if an error occurs
  98465. */
  98466. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98467. var onload = function () {
  98468. onSuccess();
  98469. };
  98470. var onerror = function (message, exception) {
  98471. onError(message, exception);
  98472. };
  98473. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98474. };
  98475. return TextureAssetTask;
  98476. }(AbstractAssetTask));
  98477. BABYLON.TextureAssetTask = TextureAssetTask;
  98478. /**
  98479. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98480. */
  98481. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98482. __extends(CubeTextureAssetTask, _super);
  98483. /**
  98484. * Creates a new CubeTextureAssetTask
  98485. * @param name defines the name of the task
  98486. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98487. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98488. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98489. * @param files defines the explicit list of files (undefined by default)
  98490. */
  98491. function CubeTextureAssetTask(
  98492. /**
  98493. * Defines the name of the task
  98494. */
  98495. name,
  98496. /**
  98497. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98498. */
  98499. url,
  98500. /**
  98501. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98502. */
  98503. extensions,
  98504. /**
  98505. * Defines if mipmaps should not be generated (default is false)
  98506. */
  98507. noMipmap,
  98508. /**
  98509. * Defines the explicit list of files (undefined by default)
  98510. */
  98511. files) {
  98512. var _this = _super.call(this, name) || this;
  98513. _this.name = name;
  98514. _this.url = url;
  98515. _this.extensions = extensions;
  98516. _this.noMipmap = noMipmap;
  98517. _this.files = files;
  98518. return _this;
  98519. }
  98520. /**
  98521. * Execute the current task
  98522. * @param scene defines the scene where you want your assets to be loaded
  98523. * @param onSuccess is a callback called when the task is successfully executed
  98524. * @param onError is a callback called if an error occurs
  98525. */
  98526. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98527. var onload = function () {
  98528. onSuccess();
  98529. };
  98530. var onerror = function (message, exception) {
  98531. onError(message, exception);
  98532. };
  98533. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98534. };
  98535. return CubeTextureAssetTask;
  98536. }(AbstractAssetTask));
  98537. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98538. /**
  98539. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98540. */
  98541. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98542. __extends(HDRCubeTextureAssetTask, _super);
  98543. /**
  98544. * Creates a new HDRCubeTextureAssetTask object
  98545. * @param name defines the name of the task
  98546. * @param url defines the location of the file to load
  98547. * @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.
  98548. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98549. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98550. * @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)
  98551. * @param reserved Internal use only
  98552. */
  98553. function HDRCubeTextureAssetTask(
  98554. /**
  98555. * Defines the name of the task
  98556. */
  98557. name,
  98558. /**
  98559. * Defines the location of the file to load
  98560. */
  98561. url,
  98562. /**
  98563. * Defines the desired size (the more it increases the longer the generation will be)
  98564. */
  98565. size,
  98566. /**
  98567. * Defines if mipmaps should not be generated (default is false)
  98568. */
  98569. noMipmap,
  98570. /**
  98571. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98572. */
  98573. generateHarmonics,
  98574. /**
  98575. * 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)
  98576. */
  98577. gammaSpace,
  98578. /**
  98579. * Internal Use Only
  98580. */
  98581. reserved) {
  98582. if (noMipmap === void 0) { noMipmap = false; }
  98583. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98584. if (gammaSpace === void 0) { gammaSpace = false; }
  98585. if (reserved === void 0) { reserved = false; }
  98586. var _this = _super.call(this, name) || this;
  98587. _this.name = name;
  98588. _this.url = url;
  98589. _this.size = size;
  98590. _this.noMipmap = noMipmap;
  98591. _this.generateHarmonics = generateHarmonics;
  98592. _this.gammaSpace = gammaSpace;
  98593. _this.reserved = reserved;
  98594. return _this;
  98595. }
  98596. /**
  98597. * Execute the current task
  98598. * @param scene defines the scene where you want your assets to be loaded
  98599. * @param onSuccess is a callback called when the task is successfully executed
  98600. * @param onError is a callback called if an error occurs
  98601. */
  98602. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98603. var onload = function () {
  98604. onSuccess();
  98605. };
  98606. var onerror = function (message, exception) {
  98607. onError(message, exception);
  98608. };
  98609. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98610. };
  98611. return HDRCubeTextureAssetTask;
  98612. }(AbstractAssetTask));
  98613. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98614. /**
  98615. * This class can be used to easily import assets into a scene
  98616. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98617. */
  98618. var AssetsManager = /** @class */ (function () {
  98619. /**
  98620. * Creates a new AssetsManager
  98621. * @param scene defines the scene to work on
  98622. */
  98623. function AssetsManager(scene) {
  98624. this._isLoading = false;
  98625. this._tasks = new Array();
  98626. this._waitingTasksCount = 0;
  98627. this._totalTasksCount = 0;
  98628. /**
  98629. * Observable called when all tasks are processed
  98630. */
  98631. this.onTaskSuccessObservable = new BABYLON.Observable();
  98632. /**
  98633. * Observable called when a task had an error
  98634. */
  98635. this.onTaskErrorObservable = new BABYLON.Observable();
  98636. /**
  98637. * Observable called when a task is successful
  98638. */
  98639. this.onTasksDoneObservable = new BABYLON.Observable();
  98640. /**
  98641. * Observable called when a task is done (whatever the result is)
  98642. */
  98643. this.onProgressObservable = new BABYLON.Observable();
  98644. /**
  98645. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98646. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98647. */
  98648. this.useDefaultLoadingScreen = true;
  98649. this._scene = scene;
  98650. }
  98651. /**
  98652. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98653. * @param taskName defines the name of the new task
  98654. * @param meshesNames defines the name of meshes to load
  98655. * @param rootUrl defines the root url to use to locate files
  98656. * @param sceneFilename defines the filename of the scene file
  98657. * @returns a new {BABYLON.MeshAssetTask} object
  98658. */
  98659. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98660. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98661. this._tasks.push(task);
  98662. return task;
  98663. };
  98664. /**
  98665. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98666. * @param taskName defines the name of the new task
  98667. * @param url defines the url of the file to load
  98668. * @returns a new {BABYLON.TextFileAssetTask} object
  98669. */
  98670. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98671. var task = new TextFileAssetTask(taskName, url);
  98672. this._tasks.push(task);
  98673. return task;
  98674. };
  98675. /**
  98676. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98677. * @param taskName defines the name of the new task
  98678. * @param url defines the url of the file to load
  98679. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98680. */
  98681. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98682. var task = new BinaryFileAssetTask(taskName, url);
  98683. this._tasks.push(task);
  98684. return task;
  98685. };
  98686. /**
  98687. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98688. * @param taskName defines the name of the new task
  98689. * @param url defines the url of the file to load
  98690. * @returns a new {BABYLON.ImageAssetTask} object
  98691. */
  98692. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98693. var task = new ImageAssetTask(taskName, url);
  98694. this._tasks.push(task);
  98695. return task;
  98696. };
  98697. /**
  98698. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98699. * @param taskName defines the name of the new task
  98700. * @param url defines the url of the file to load
  98701. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98702. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98703. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98704. * @returns a new {BABYLON.TextureAssetTask} object
  98705. */
  98706. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98707. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98708. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98709. this._tasks.push(task);
  98710. return task;
  98711. };
  98712. /**
  98713. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98714. * @param taskName defines the name of the new task
  98715. * @param url defines the url of the file to load
  98716. * @param extensions defines the extension to use to load the cube map (can be null)
  98717. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98718. * @param files defines the list of files to load (can be null)
  98719. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98720. */
  98721. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98722. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98723. this._tasks.push(task);
  98724. return task;
  98725. };
  98726. /**
  98727. *
  98728. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98729. * @param taskName defines the name of the new task
  98730. * @param url defines the url of the file to load
  98731. * @param size defines the size you want for the cubemap (can be null)
  98732. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98733. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98734. * @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)
  98735. * @param reserved Internal use only
  98736. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98737. */
  98738. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98739. if (noMipmap === void 0) { noMipmap = false; }
  98740. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98741. if (gammaSpace === void 0) { gammaSpace = false; }
  98742. if (reserved === void 0) { reserved = false; }
  98743. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98744. this._tasks.push(task);
  98745. return task;
  98746. };
  98747. /**
  98748. * Remove a task from the assets manager.
  98749. * @param task the task to remove
  98750. */
  98751. AssetsManager.prototype.removeTask = function (task) {
  98752. var index = this._tasks.indexOf(task);
  98753. if (index > -1) {
  98754. this._tasks.splice(index, 1);
  98755. }
  98756. };
  98757. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98758. this._waitingTasksCount--;
  98759. try {
  98760. if (this.onProgress) {
  98761. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98762. }
  98763. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98764. }
  98765. catch (e) {
  98766. BABYLON.Tools.Error("Error running progress callbacks.");
  98767. console.log(e);
  98768. }
  98769. if (this._waitingTasksCount === 0) {
  98770. try {
  98771. if (this.onFinish) {
  98772. this.onFinish(this._tasks);
  98773. }
  98774. // Let's remove successfull tasks
  98775. var currentTasks = this._tasks.slice();
  98776. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98777. var task = currentTasks_1[_i];
  98778. if (task.taskState === AssetTaskState.DONE) {
  98779. var index = this._tasks.indexOf(task);
  98780. if (index > -1) {
  98781. this._tasks.splice(index, 1);
  98782. }
  98783. }
  98784. }
  98785. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98786. }
  98787. catch (e) {
  98788. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98789. console.log(e);
  98790. }
  98791. this._isLoading = false;
  98792. this._scene.getEngine().hideLoadingUI();
  98793. }
  98794. };
  98795. AssetsManager.prototype._runTask = function (task) {
  98796. var _this = this;
  98797. var done = function () {
  98798. try {
  98799. if (_this.onTaskSuccess) {
  98800. _this.onTaskSuccess(task);
  98801. }
  98802. _this.onTaskSuccessObservable.notifyObservers(task);
  98803. _this._decreaseWaitingTasksCount(task);
  98804. }
  98805. catch (e) {
  98806. error("Error executing task success callbacks", e);
  98807. }
  98808. };
  98809. var error = function (message, exception) {
  98810. task._setErrorObject(message, exception);
  98811. if (_this.onTaskError) {
  98812. _this.onTaskError(task);
  98813. }
  98814. _this.onTaskErrorObservable.notifyObservers(task);
  98815. _this._decreaseWaitingTasksCount(task);
  98816. };
  98817. task.run(this._scene, done, error);
  98818. };
  98819. /**
  98820. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98821. * @return the current instance of the {BABYLON.AssetsManager}
  98822. */
  98823. AssetsManager.prototype.reset = function () {
  98824. this._isLoading = false;
  98825. this._tasks = new Array();
  98826. return this;
  98827. };
  98828. /**
  98829. * Start the loading process
  98830. * @return the current instance of the {BABYLON.AssetsManager}
  98831. */
  98832. AssetsManager.prototype.load = function () {
  98833. if (this._isLoading) {
  98834. return this;
  98835. }
  98836. this._isLoading = true;
  98837. this._waitingTasksCount = this._tasks.length;
  98838. this._totalTasksCount = this._tasks.length;
  98839. if (this._waitingTasksCount === 0) {
  98840. this._isLoading = false;
  98841. if (this.onFinish) {
  98842. this.onFinish(this._tasks);
  98843. }
  98844. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98845. return this;
  98846. }
  98847. if (this.useDefaultLoadingScreen) {
  98848. this._scene.getEngine().displayLoadingUI();
  98849. }
  98850. for (var index = 0; index < this._tasks.length; index++) {
  98851. var task = this._tasks[index];
  98852. if (task.taskState === AssetTaskState.INIT) {
  98853. this._runTask(task);
  98854. }
  98855. }
  98856. return this;
  98857. };
  98858. return AssetsManager;
  98859. }());
  98860. BABYLON.AssetsManager = AssetsManager;
  98861. })(BABYLON || (BABYLON = {}));
  98862. //# sourceMappingURL=babylon.assetsManager.js.map
  98863. var BABYLON;
  98864. (function (BABYLON) {
  98865. var serializedGeometries = [];
  98866. var serializeGeometry = function (geometry, serializationGeometries) {
  98867. if (serializedGeometries[geometry.id]) {
  98868. return;
  98869. }
  98870. if (geometry.doNotSerialize) {
  98871. return;
  98872. }
  98873. if (geometry instanceof BABYLON.BoxGeometry) {
  98874. serializationGeometries.boxes.push(geometry.serialize());
  98875. }
  98876. else if (geometry instanceof BABYLON.SphereGeometry) {
  98877. serializationGeometries.spheres.push(geometry.serialize());
  98878. }
  98879. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98880. serializationGeometries.cylinders.push(geometry.serialize());
  98881. }
  98882. else if (geometry instanceof BABYLON.TorusGeometry) {
  98883. serializationGeometries.toruses.push(geometry.serialize());
  98884. }
  98885. else if (geometry instanceof BABYLON.GroundGeometry) {
  98886. serializationGeometries.grounds.push(geometry.serialize());
  98887. }
  98888. else if (geometry instanceof BABYLON.Plane) {
  98889. serializationGeometries.planes.push(geometry.serialize());
  98890. }
  98891. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98892. serializationGeometries.torusKnots.push(geometry.serialize());
  98893. }
  98894. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98895. throw new Error("Unknown primitive type");
  98896. }
  98897. else {
  98898. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98899. }
  98900. serializedGeometries[geometry.id] = true;
  98901. };
  98902. var serializeMesh = function (mesh, serializationScene) {
  98903. var serializationObject = {};
  98904. // Geometry
  98905. var geometry = mesh._geometry;
  98906. if (geometry) {
  98907. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98908. // 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
  98909. serializeGeometry(geometry, serializationScene.geometries);
  98910. }
  98911. }
  98912. // Custom
  98913. if (mesh.serialize) {
  98914. mesh.serialize(serializationObject);
  98915. }
  98916. return serializationObject;
  98917. };
  98918. var finalizeSingleMesh = function (mesh, serializationObject) {
  98919. //only works if the mesh is already loaded
  98920. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98921. //serialize material
  98922. if (mesh.material) {
  98923. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98924. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98925. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98926. serializationObject.multiMaterials.push(mesh.material.serialize());
  98927. }
  98928. }
  98929. else {
  98930. serializationObject.materials = serializationObject.materials || [];
  98931. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98932. serializationObject.materials.push(mesh.material.serialize());
  98933. }
  98934. }
  98935. }
  98936. //serialize geometry
  98937. var geometry = mesh._geometry;
  98938. if (geometry) {
  98939. if (!serializationObject.geometries) {
  98940. serializationObject.geometries = {};
  98941. serializationObject.geometries.boxes = [];
  98942. serializationObject.geometries.spheres = [];
  98943. serializationObject.geometries.cylinders = [];
  98944. serializationObject.geometries.toruses = [];
  98945. serializationObject.geometries.grounds = [];
  98946. serializationObject.geometries.planes = [];
  98947. serializationObject.geometries.torusKnots = [];
  98948. serializationObject.geometries.vertexData = [];
  98949. }
  98950. serializeGeometry(geometry, serializationObject.geometries);
  98951. }
  98952. // Skeletons
  98953. if (mesh.skeleton) {
  98954. serializationObject.skeletons = serializationObject.skeletons || [];
  98955. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98956. }
  98957. //serialize the actual mesh
  98958. serializationObject.meshes = serializationObject.meshes || [];
  98959. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98960. }
  98961. };
  98962. var SceneSerializer = /** @class */ (function () {
  98963. function SceneSerializer() {
  98964. }
  98965. SceneSerializer.ClearCache = function () {
  98966. serializedGeometries = [];
  98967. };
  98968. SceneSerializer.Serialize = function (scene) {
  98969. var serializationObject = {};
  98970. SceneSerializer.ClearCache();
  98971. // Scene
  98972. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98973. serializationObject.autoClear = scene.autoClear;
  98974. serializationObject.clearColor = scene.clearColor.asArray();
  98975. serializationObject.ambientColor = scene.ambientColor.asArray();
  98976. serializationObject.gravity = scene.gravity.asArray();
  98977. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98978. serializationObject.workerCollisions = scene.workerCollisions;
  98979. // Fog
  98980. if (scene.fogMode && scene.fogMode !== 0) {
  98981. serializationObject.fogMode = scene.fogMode;
  98982. serializationObject.fogColor = scene.fogColor.asArray();
  98983. serializationObject.fogStart = scene.fogStart;
  98984. serializationObject.fogEnd = scene.fogEnd;
  98985. serializationObject.fogDensity = scene.fogDensity;
  98986. }
  98987. //Physics
  98988. if (scene.isPhysicsEnabled()) {
  98989. var physicEngine = scene.getPhysicsEngine();
  98990. if (physicEngine) {
  98991. serializationObject.physicsEnabled = true;
  98992. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98993. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98994. }
  98995. }
  98996. // Metadata
  98997. if (scene.metadata) {
  98998. serializationObject.metadata = scene.metadata;
  98999. }
  99000. // Morph targets
  99001. serializationObject.morphTargetManagers = [];
  99002. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99003. var abstractMesh = _a[_i];
  99004. var manager = abstractMesh.morphTargetManager;
  99005. if (manager) {
  99006. serializationObject.morphTargetManagers.push(manager.serialize());
  99007. }
  99008. }
  99009. // Lights
  99010. serializationObject.lights = [];
  99011. var index;
  99012. var light;
  99013. for (index = 0; index < scene.lights.length; index++) {
  99014. light = scene.lights[index];
  99015. if (!light.doNotSerialize) {
  99016. serializationObject.lights.push(light.serialize());
  99017. }
  99018. }
  99019. // Cameras
  99020. serializationObject.cameras = [];
  99021. for (index = 0; index < scene.cameras.length; index++) {
  99022. var camera = scene.cameras[index];
  99023. if (!camera.doNotSerialize) {
  99024. serializationObject.cameras.push(camera.serialize());
  99025. }
  99026. }
  99027. if (scene.activeCamera) {
  99028. serializationObject.activeCameraID = scene.activeCamera.id;
  99029. }
  99030. // Animations
  99031. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99032. // Materials
  99033. serializationObject.materials = [];
  99034. serializationObject.multiMaterials = [];
  99035. var material;
  99036. for (index = 0; index < scene.materials.length; index++) {
  99037. material = scene.materials[index];
  99038. if (!material.doNotSerialize) {
  99039. serializationObject.materials.push(material.serialize());
  99040. }
  99041. }
  99042. // MultiMaterials
  99043. serializationObject.multiMaterials = [];
  99044. for (index = 0; index < scene.multiMaterials.length; index++) {
  99045. var multiMaterial = scene.multiMaterials[index];
  99046. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99047. }
  99048. // Environment texture
  99049. if (scene.environmentTexture) {
  99050. serializationObject.environmentTexture = scene.environmentTexture.name;
  99051. }
  99052. // Skeletons
  99053. serializationObject.skeletons = [];
  99054. for (index = 0; index < scene.skeletons.length; index++) {
  99055. var skeleton = scene.skeletons[index];
  99056. if (!skeleton.doNotSerialize) {
  99057. serializationObject.skeletons.push(skeleton.serialize());
  99058. }
  99059. }
  99060. // Transform nodes
  99061. serializationObject.transformNodes = [];
  99062. for (index = 0; index < scene.transformNodes.length; index++) {
  99063. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99064. }
  99065. // Geometries
  99066. serializationObject.geometries = {};
  99067. serializationObject.geometries.boxes = [];
  99068. serializationObject.geometries.spheres = [];
  99069. serializationObject.geometries.cylinders = [];
  99070. serializationObject.geometries.toruses = [];
  99071. serializationObject.geometries.grounds = [];
  99072. serializationObject.geometries.planes = [];
  99073. serializationObject.geometries.torusKnots = [];
  99074. serializationObject.geometries.vertexData = [];
  99075. serializedGeometries = [];
  99076. var geometries = scene.getGeometries();
  99077. for (index = 0; index < geometries.length; index++) {
  99078. var geometry = geometries[index];
  99079. if (geometry.isReady()) {
  99080. serializeGeometry(geometry, serializationObject.geometries);
  99081. }
  99082. }
  99083. // Meshes
  99084. serializationObject.meshes = [];
  99085. for (index = 0; index < scene.meshes.length; index++) {
  99086. var abstractMesh = scene.meshes[index];
  99087. if (abstractMesh instanceof BABYLON.Mesh) {
  99088. var mesh = abstractMesh;
  99089. if (!mesh.doNotSerialize) {
  99090. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99091. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99092. }
  99093. }
  99094. }
  99095. }
  99096. // Particles Systems
  99097. serializationObject.particleSystems = [];
  99098. for (index = 0; index < scene.particleSystems.length; index++) {
  99099. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99100. }
  99101. // Shadows
  99102. serializationObject.shadowGenerators = [];
  99103. for (index = 0; index < scene.lights.length; index++) {
  99104. light = scene.lights[index];
  99105. var shadowGenerator = light.getShadowGenerator();
  99106. if (shadowGenerator) {
  99107. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99108. }
  99109. }
  99110. // Action Manager
  99111. if (scene.actionManager) {
  99112. serializationObject.actions = scene.actionManager.serialize("scene");
  99113. }
  99114. // Audio
  99115. serializationObject.sounds = [];
  99116. for (index = 0; index < scene.soundTracks.length; index++) {
  99117. var soundtrack = scene.soundTracks[index];
  99118. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99119. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99120. }
  99121. }
  99122. // Components
  99123. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99124. var component = _c[_b];
  99125. component.serialize(serializationObject);
  99126. }
  99127. return serializationObject;
  99128. };
  99129. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99130. if (withParents === void 0) { withParents = false; }
  99131. if (withChildren === void 0) { withChildren = false; }
  99132. var serializationObject = {};
  99133. SceneSerializer.ClearCache();
  99134. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99135. if (withParents || withChildren) {
  99136. //deliberate for loop! not for each, appended should be processed as well.
  99137. for (var i = 0; i < toSerialize.length; ++i) {
  99138. if (withChildren) {
  99139. toSerialize[i].getDescendants().forEach(function (node) {
  99140. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99141. toSerialize.push(node);
  99142. }
  99143. });
  99144. }
  99145. //make sure the array doesn't contain the object already
  99146. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99147. toSerialize.push(toSerialize[i].parent);
  99148. }
  99149. }
  99150. }
  99151. toSerialize.forEach(function (mesh) {
  99152. finalizeSingleMesh(mesh, serializationObject);
  99153. });
  99154. return serializationObject;
  99155. };
  99156. return SceneSerializer;
  99157. }());
  99158. BABYLON.SceneSerializer = SceneSerializer;
  99159. })(BABYLON || (BABYLON = {}));
  99160. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99161. var BABYLON;
  99162. (function (BABYLON) {
  99163. var ReflectionProbe = /** @class */ (function () {
  99164. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99165. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99166. var _this = this;
  99167. this.name = name;
  99168. this._viewMatrix = BABYLON.Matrix.Identity();
  99169. this._target = BABYLON.Vector3.Zero();
  99170. this._add = BABYLON.Vector3.Zero();
  99171. this._invertYAxis = false;
  99172. this.position = BABYLON.Vector3.Zero();
  99173. this._scene = scene;
  99174. this._scene.reflectionProbes.push(this);
  99175. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99176. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99177. switch (faceIndex) {
  99178. case 0:
  99179. _this._add.copyFromFloats(1, 0, 0);
  99180. break;
  99181. case 1:
  99182. _this._add.copyFromFloats(-1, 0, 0);
  99183. break;
  99184. case 2:
  99185. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99186. break;
  99187. case 3:
  99188. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99189. break;
  99190. case 4:
  99191. _this._add.copyFromFloats(0, 0, 1);
  99192. break;
  99193. case 5:
  99194. _this._add.copyFromFloats(0, 0, -1);
  99195. break;
  99196. }
  99197. if (_this._attachedMesh) {
  99198. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99199. }
  99200. _this.position.addToRef(_this._add, _this._target);
  99201. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99202. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99203. scene._forcedViewPosition = _this.position;
  99204. });
  99205. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99206. scene._forcedViewPosition = null;
  99207. scene.updateTransformMatrix(true);
  99208. });
  99209. if (scene.activeCamera) {
  99210. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99211. }
  99212. }
  99213. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99214. get: function () {
  99215. return this._renderTargetTexture.samples;
  99216. },
  99217. set: function (value) {
  99218. this._renderTargetTexture.samples = value;
  99219. },
  99220. enumerable: true,
  99221. configurable: true
  99222. });
  99223. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99224. get: function () {
  99225. return this._renderTargetTexture.refreshRate;
  99226. },
  99227. set: function (value) {
  99228. this._renderTargetTexture.refreshRate = value;
  99229. },
  99230. enumerable: true,
  99231. configurable: true
  99232. });
  99233. ReflectionProbe.prototype.getScene = function () {
  99234. return this._scene;
  99235. };
  99236. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99237. get: function () {
  99238. return this._renderTargetTexture;
  99239. },
  99240. enumerable: true,
  99241. configurable: true
  99242. });
  99243. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99244. get: function () {
  99245. return this._renderTargetTexture.renderList;
  99246. },
  99247. enumerable: true,
  99248. configurable: true
  99249. });
  99250. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99251. this._attachedMesh = mesh;
  99252. };
  99253. /**
  99254. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99255. *
  99256. * @param renderingGroupId The rendering group id corresponding to its index
  99257. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99258. */
  99259. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99260. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99261. };
  99262. ReflectionProbe.prototype.dispose = function () {
  99263. var index = this._scene.reflectionProbes.indexOf(this);
  99264. if (index !== -1) {
  99265. // Remove from the scene if found
  99266. this._scene.reflectionProbes.splice(index, 1);
  99267. }
  99268. if (this._renderTargetTexture) {
  99269. this._renderTargetTexture.dispose();
  99270. this._renderTargetTexture = null;
  99271. }
  99272. };
  99273. return ReflectionProbe;
  99274. }());
  99275. BABYLON.ReflectionProbe = ReflectionProbe;
  99276. })(BABYLON || (BABYLON = {}));
  99277. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99278. var BABYLON;
  99279. (function (BABYLON) {
  99280. /**
  99281. * Defines the layer scene component responsible to manage any layers
  99282. * in a given scene.
  99283. */
  99284. var LayerSceneComponent = /** @class */ (function () {
  99285. /**
  99286. * Creates a new instance of the component for the given scene
  99287. * @param scene Defines the scene to register the component in
  99288. */
  99289. function LayerSceneComponent(scene) {
  99290. /**
  99291. * The component name helpfull to identify the component in the list of scene components.
  99292. */
  99293. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99294. this.scene = scene;
  99295. this._engine = scene.getEngine();
  99296. scene.layers = new Array();
  99297. }
  99298. /**
  99299. * Registers the component in a given scene
  99300. */
  99301. LayerSceneComponent.prototype.register = function () {
  99302. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99303. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99304. };
  99305. /**
  99306. * Rebuilds the elements related to this component in case of
  99307. * context lost for instance.
  99308. */
  99309. LayerSceneComponent.prototype.rebuild = function () {
  99310. var layers = this.scene.layers;
  99311. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99312. var layer = layers_1[_i];
  99313. layer._rebuild();
  99314. }
  99315. };
  99316. /**
  99317. * Disposes the component and the associated ressources.
  99318. */
  99319. LayerSceneComponent.prototype.dispose = function () {
  99320. var layers = this.scene.layers;
  99321. while (layers.length) {
  99322. layers[0].dispose();
  99323. }
  99324. };
  99325. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99326. var layers = this.scene.layers;
  99327. if (layers.length) {
  99328. this._engine.setDepthBuffer(false);
  99329. var cameraLayerMask = camera.layerMask;
  99330. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99331. var layer = layers_2[_i];
  99332. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99333. layer.render();
  99334. }
  99335. }
  99336. this._engine.setDepthBuffer(true);
  99337. }
  99338. };
  99339. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99340. this._draw(camera, true);
  99341. };
  99342. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99343. this._draw(camera, false);
  99344. };
  99345. return LayerSceneComponent;
  99346. }());
  99347. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99348. })(BABYLON || (BABYLON = {}));
  99349. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99350. var BABYLON;
  99351. (function (BABYLON) {
  99352. var Layer = /** @class */ (function () {
  99353. function Layer(name, imgUrl, scene, isBackground, color) {
  99354. this.name = name;
  99355. this.scale = new BABYLON.Vector2(1, 1);
  99356. this.offset = new BABYLON.Vector2(0, 0);
  99357. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99358. this.layerMask = 0x0FFFFFFF;
  99359. this._vertexBuffers = {};
  99360. // Events
  99361. /**
  99362. * An event triggered when the layer is disposed.
  99363. */
  99364. this.onDisposeObservable = new BABYLON.Observable();
  99365. /**
  99366. * An event triggered before rendering the scene
  99367. */
  99368. this.onBeforeRenderObservable = new BABYLON.Observable();
  99369. /**
  99370. * An event triggered after rendering the scene
  99371. */
  99372. this.onAfterRenderObservable = new BABYLON.Observable();
  99373. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99374. this.isBackground = isBackground === undefined ? true : isBackground;
  99375. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99376. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99377. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99378. if (!layerComponent) {
  99379. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99380. this._scene._addComponent(layerComponent);
  99381. }
  99382. this._scene.layers.push(this);
  99383. var engine = this._scene.getEngine();
  99384. // VBO
  99385. var vertices = [];
  99386. vertices.push(1, 1);
  99387. vertices.push(-1, 1);
  99388. vertices.push(-1, -1);
  99389. vertices.push(1, -1);
  99390. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99392. this._createIndexBuffer();
  99393. // Effects
  99394. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99395. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99396. }
  99397. Object.defineProperty(Layer.prototype, "onDispose", {
  99398. set: function (callback) {
  99399. if (this._onDisposeObserver) {
  99400. this.onDisposeObservable.remove(this._onDisposeObserver);
  99401. }
  99402. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99403. },
  99404. enumerable: true,
  99405. configurable: true
  99406. });
  99407. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99408. set: function (callback) {
  99409. if (this._onBeforeRenderObserver) {
  99410. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99411. }
  99412. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99413. },
  99414. enumerable: true,
  99415. configurable: true
  99416. });
  99417. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99418. set: function (callback) {
  99419. if (this._onAfterRenderObserver) {
  99420. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99421. }
  99422. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99423. },
  99424. enumerable: true,
  99425. configurable: true
  99426. });
  99427. Layer.prototype._createIndexBuffer = function () {
  99428. var engine = this._scene.getEngine();
  99429. // Indices
  99430. var indices = [];
  99431. indices.push(0);
  99432. indices.push(1);
  99433. indices.push(2);
  99434. indices.push(0);
  99435. indices.push(2);
  99436. indices.push(3);
  99437. this._indexBuffer = engine.createIndexBuffer(indices);
  99438. };
  99439. Layer.prototype._rebuild = function () {
  99440. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99441. if (vb) {
  99442. vb._rebuild();
  99443. }
  99444. this._createIndexBuffer();
  99445. };
  99446. Layer.prototype.render = function () {
  99447. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99448. // Check
  99449. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99450. return;
  99451. var engine = this._scene.getEngine();
  99452. this.onBeforeRenderObservable.notifyObservers(this);
  99453. // Render
  99454. engine.enableEffect(currentEffect);
  99455. engine.setState(false);
  99456. // Texture
  99457. currentEffect.setTexture("textureSampler", this.texture);
  99458. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99459. // Color
  99460. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99461. // Scale / offset
  99462. currentEffect.setVector2("offset", this.offset);
  99463. currentEffect.setVector2("scale", this.scale);
  99464. // VBOs
  99465. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99466. // Draw order
  99467. if (!this.alphaTest) {
  99468. engine.setAlphaMode(this.alphaBlendingMode);
  99469. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99470. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99471. }
  99472. else {
  99473. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99474. }
  99475. this.onAfterRenderObservable.notifyObservers(this);
  99476. };
  99477. Layer.prototype.dispose = function () {
  99478. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99479. if (vertexBuffer) {
  99480. vertexBuffer.dispose();
  99481. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99482. }
  99483. if (this._indexBuffer) {
  99484. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99485. this._indexBuffer = null;
  99486. }
  99487. if (this.texture) {
  99488. this.texture.dispose();
  99489. this.texture = null;
  99490. }
  99491. // Remove from scene
  99492. var index = this._scene.layers.indexOf(this);
  99493. this._scene.layers.splice(index, 1);
  99494. // Callback
  99495. this.onDisposeObservable.notifyObservers(this);
  99496. this.onDisposeObservable.clear();
  99497. this.onAfterRenderObservable.clear();
  99498. this.onBeforeRenderObservable.clear();
  99499. };
  99500. return Layer;
  99501. }());
  99502. BABYLON.Layer = Layer;
  99503. })(BABYLON || (BABYLON = {}));
  99504. //# sourceMappingURL=babylon.layer.js.map
  99505. var BABYLON;
  99506. (function (BABYLON) {
  99507. var TextureTools = /** @class */ (function () {
  99508. function TextureTools() {
  99509. }
  99510. /**
  99511. * Uses the GPU to create a copy texture rescaled at a given size
  99512. * @param texture Texture to copy from
  99513. * @param width Desired width
  99514. * @param height Desired height
  99515. * @return Generated texture
  99516. */
  99517. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99518. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99519. var scene = texture.getScene();
  99520. var engine = scene.getEngine();
  99521. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99522. rtt.wrapU = texture.wrapU;
  99523. rtt.wrapV = texture.wrapV;
  99524. rtt.uOffset = texture.uOffset;
  99525. rtt.vOffset = texture.vOffset;
  99526. rtt.uScale = texture.uScale;
  99527. rtt.vScale = texture.vScale;
  99528. rtt.uAng = texture.uAng;
  99529. rtt.vAng = texture.vAng;
  99530. rtt.wAng = texture.wAng;
  99531. rtt.coordinatesIndex = texture.coordinatesIndex;
  99532. rtt.level = texture.level;
  99533. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99534. rtt._texture.isReady = false;
  99535. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99536. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99537. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99538. passPostProcess.getEffect().executeWhenCompiled(function () {
  99539. passPostProcess.onApply = function (effect) {
  99540. effect.setTexture("textureSampler", texture);
  99541. };
  99542. var internalTexture = rtt.getInternalTexture();
  99543. if (internalTexture) {
  99544. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99545. engine.unBindFramebuffer(internalTexture);
  99546. rtt.disposeFramebufferObjects();
  99547. passPostProcess.dispose();
  99548. internalTexture.isReady = true;
  99549. }
  99550. });
  99551. return rtt;
  99552. };
  99553. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99554. if (!scene._environmentBRDFTexture) {
  99555. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99556. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99557. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99558. scene._environmentBRDFTexture = texture;
  99559. }
  99560. return scene._environmentBRDFTexture;
  99561. };
  99562. 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=";
  99563. return TextureTools;
  99564. }());
  99565. BABYLON.TextureTools = TextureTools;
  99566. })(BABYLON || (BABYLON = {}));
  99567. //# sourceMappingURL=babylon.textureTools.js.map
  99568. var BABYLON;
  99569. (function (BABYLON) {
  99570. var FramingBehavior = /** @class */ (function () {
  99571. function FramingBehavior() {
  99572. this._mode = FramingBehavior.FitFrustumSidesMode;
  99573. this._radiusScale = 1.0;
  99574. this._positionScale = 0.5;
  99575. this._defaultElevation = 0.3;
  99576. this._elevationReturnTime = 1500;
  99577. this._elevationReturnWaitTime = 1000;
  99578. this._zoomStopsAnimation = false;
  99579. this._framingTime = 1500;
  99580. this._isPointerDown = false;
  99581. this._lastInteractionTime = -Infinity;
  99582. // Framing control
  99583. this._animatables = new Array();
  99584. this._betaIsAnimating = false;
  99585. }
  99586. Object.defineProperty(FramingBehavior.prototype, "name", {
  99587. get: function () {
  99588. return "Framing";
  99589. },
  99590. enumerable: true,
  99591. configurable: true
  99592. });
  99593. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99594. /**
  99595. * Gets current mode used by the behavior.
  99596. */
  99597. get: function () {
  99598. return this._mode;
  99599. },
  99600. /**
  99601. * Sets the current mode used by the behavior
  99602. */
  99603. set: function (mode) {
  99604. this._mode = mode;
  99605. },
  99606. enumerable: true,
  99607. configurable: true
  99608. });
  99609. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99610. /**
  99611. * Gets the scale applied to the radius
  99612. */
  99613. get: function () {
  99614. return this._radiusScale;
  99615. },
  99616. /**
  99617. * Sets the scale applied to the radius (1 by default)
  99618. */
  99619. set: function (radius) {
  99620. this._radiusScale = radius;
  99621. },
  99622. enumerable: true,
  99623. configurable: true
  99624. });
  99625. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99626. /**
  99627. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99628. */
  99629. get: function () {
  99630. return this._positionScale;
  99631. },
  99632. /**
  99633. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99634. */
  99635. set: function (scale) {
  99636. this._positionScale = scale;
  99637. },
  99638. enumerable: true,
  99639. configurable: true
  99640. });
  99641. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99642. /**
  99643. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99644. * behaviour is triggered, in radians.
  99645. */
  99646. get: function () {
  99647. return this._defaultElevation;
  99648. },
  99649. /**
  99650. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99651. * behaviour is triggered, in radians.
  99652. */
  99653. set: function (elevation) {
  99654. this._defaultElevation = elevation;
  99655. },
  99656. enumerable: true,
  99657. configurable: true
  99658. });
  99659. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99660. /**
  99661. * Gets the time (in milliseconds) taken to return to the default beta position.
  99662. * Negative value indicates camera should not return to default.
  99663. */
  99664. get: function () {
  99665. return this._elevationReturnTime;
  99666. },
  99667. /**
  99668. * Sets the time (in milliseconds) taken to return to the default beta position.
  99669. * Negative value indicates camera should not return to default.
  99670. */
  99671. set: function (speed) {
  99672. this._elevationReturnTime = speed;
  99673. },
  99674. enumerable: true,
  99675. configurable: true
  99676. });
  99677. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99678. /**
  99679. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99680. */
  99681. get: function () {
  99682. return this._elevationReturnWaitTime;
  99683. },
  99684. /**
  99685. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99686. */
  99687. set: function (time) {
  99688. this._elevationReturnWaitTime = time;
  99689. },
  99690. enumerable: true,
  99691. configurable: true
  99692. });
  99693. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99694. /**
  99695. * Gets the flag that indicates if user zooming should stop animation.
  99696. */
  99697. get: function () {
  99698. return this._zoomStopsAnimation;
  99699. },
  99700. /**
  99701. * Sets the flag that indicates if user zooming should stop animation.
  99702. */
  99703. set: function (flag) {
  99704. this._zoomStopsAnimation = flag;
  99705. },
  99706. enumerable: true,
  99707. configurable: true
  99708. });
  99709. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99710. /**
  99711. * Gets the transition time when framing the mesh, in milliseconds
  99712. */
  99713. get: function () {
  99714. return this._framingTime;
  99715. },
  99716. /**
  99717. * Sets the transition time when framing the mesh, in milliseconds
  99718. */
  99719. set: function (time) {
  99720. this._framingTime = time;
  99721. },
  99722. enumerable: true,
  99723. configurable: true
  99724. });
  99725. FramingBehavior.prototype.init = function () {
  99726. // Do notihng
  99727. };
  99728. FramingBehavior.prototype.attach = function (camera) {
  99729. var _this = this;
  99730. this._attachedCamera = camera;
  99731. var scene = this._attachedCamera.getScene();
  99732. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99733. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99734. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99735. _this._isPointerDown = true;
  99736. return;
  99737. }
  99738. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99739. _this._isPointerDown = false;
  99740. }
  99741. });
  99742. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99743. if (mesh) {
  99744. _this.zoomOnMesh(mesh);
  99745. }
  99746. });
  99747. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99748. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99749. _this._applyUserInteraction();
  99750. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99751. // back to the default position after a given timeout
  99752. _this._maintainCameraAboveGround();
  99753. });
  99754. };
  99755. FramingBehavior.prototype.detach = function () {
  99756. if (!this._attachedCamera) {
  99757. return;
  99758. }
  99759. var scene = this._attachedCamera.getScene();
  99760. if (this._onPrePointerObservableObserver) {
  99761. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99762. }
  99763. if (this._onAfterCheckInputsObserver) {
  99764. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99765. }
  99766. if (this._onMeshTargetChangedObserver) {
  99767. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99768. }
  99769. this._attachedCamera = null;
  99770. };
  99771. /**
  99772. * Targets the given mesh and updates zoom level accordingly.
  99773. * @param mesh The mesh to target.
  99774. * @param radius Optional. If a cached radius position already exists, overrides default.
  99775. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99776. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99777. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99778. */
  99779. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99780. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99781. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99782. mesh.computeWorldMatrix(true);
  99783. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99784. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99785. };
  99786. /**
  99787. * Targets the given mesh with its children and updates zoom level accordingly.
  99788. * @param mesh The mesh to target.
  99789. * @param radius Optional. If a cached radius position already exists, overrides default.
  99790. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99791. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99792. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99793. */
  99794. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99795. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99796. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99797. mesh.computeWorldMatrix(true);
  99798. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99799. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99800. };
  99801. /**
  99802. * Targets the given meshes with their children and updates zoom level accordingly.
  99803. * @param meshes The mesh to target.
  99804. * @param radius Optional. If a cached radius position already exists, overrides default.
  99805. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99806. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99807. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99808. */
  99809. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99810. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99811. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99812. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99813. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99814. for (var i = 0; i < meshes.length; i++) {
  99815. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99816. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99817. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99818. }
  99819. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99820. };
  99821. /**
  99822. * Targets the given mesh and updates zoom level accordingly.
  99823. * @param mesh The mesh to target.
  99824. * @param radius Optional. If a cached radius position already exists, overrides default.
  99825. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99826. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99827. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99828. */
  99829. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99830. var _this = this;
  99831. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99832. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99833. var zoomTarget;
  99834. if (!this._attachedCamera) {
  99835. return;
  99836. }
  99837. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99838. var bottom = minimumWorld.y;
  99839. var top = maximumWorld.y;
  99840. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99841. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99842. if (focusOnOriginXZ) {
  99843. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99844. }
  99845. else {
  99846. var centerWorld = minimumWorld.add(radiusWorld);
  99847. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99848. }
  99849. if (!this._vectorTransition) {
  99850. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99851. }
  99852. this._betaIsAnimating = true;
  99853. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99854. if (animatable) {
  99855. this._animatables.push(animatable);
  99856. }
  99857. // sets the radius and lower radius bounds
  99858. // Small delta ensures camera is not always at lower zoom limit.
  99859. var radius = 0;
  99860. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99861. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99862. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99863. radius = position;
  99864. }
  99865. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99866. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99867. if (this._attachedCamera.lowerRadiusLimit === null) {
  99868. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99869. }
  99870. }
  99871. // Set sensibilities
  99872. var extend = maximumWorld.subtract(minimumWorld).length();
  99873. this._attachedCamera.panningSensibility = 5000 / extend;
  99874. this._attachedCamera.wheelPrecision = 100 / radius;
  99875. // transition to new radius
  99876. if (!this._radiusTransition) {
  99877. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99878. }
  99879. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99880. _this.stopAllAnimations();
  99881. if (onAnimationEnd) {
  99882. onAnimationEnd();
  99883. }
  99884. if (_this._attachedCamera) {
  99885. _this._attachedCamera.storeState();
  99886. }
  99887. });
  99888. if (animatable) {
  99889. this._animatables.push(animatable);
  99890. }
  99891. };
  99892. /**
  99893. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99894. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99895. * frustum width.
  99896. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99897. * to fully enclose the mesh in the viewing frustum.
  99898. */
  99899. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99900. var size = maximumWorld.subtract(minimumWorld);
  99901. var boxVectorGlobalDiagonal = size.length();
  99902. var frustumSlope = this._getFrustumSlope();
  99903. // Formula for setting distance
  99904. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99905. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99906. // Horizon distance
  99907. var radius = radiusWithoutFraming * this._radiusScale;
  99908. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99909. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99910. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99911. var camera = this._attachedCamera;
  99912. if (!camera) {
  99913. return 0;
  99914. }
  99915. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99916. // Don't exceed the requested limit
  99917. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99918. }
  99919. // Don't exceed the upper radius limit
  99920. if (camera.upperRadiusLimit) {
  99921. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99922. }
  99923. return distance;
  99924. };
  99925. /**
  99926. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99927. * is automatically returned to its default position (expected to be above ground plane).
  99928. */
  99929. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99930. var _this = this;
  99931. if (this._elevationReturnTime < 0) {
  99932. return;
  99933. }
  99934. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99935. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99936. var limitBeta = Math.PI * 0.5;
  99937. // Bring the camera back up if below the ground plane
  99938. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99939. this._betaIsAnimating = true;
  99940. //Transition to new position
  99941. this.stopAllAnimations();
  99942. if (!this._betaTransition) {
  99943. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99944. }
  99945. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99946. _this._clearAnimationLocks();
  99947. _this.stopAllAnimations();
  99948. });
  99949. if (animatabe) {
  99950. this._animatables.push(animatabe);
  99951. }
  99952. }
  99953. };
  99954. /**
  99955. * Returns the frustum slope based on the canvas ratio and camera FOV
  99956. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99957. */
  99958. FramingBehavior.prototype._getFrustumSlope = function () {
  99959. // Calculate the viewport ratio
  99960. // Aspect Ratio is Height/Width.
  99961. var camera = this._attachedCamera;
  99962. if (!camera) {
  99963. return BABYLON.Vector2.Zero();
  99964. }
  99965. var engine = camera.getScene().getEngine();
  99966. var aspectRatio = engine.getAspectRatio(camera);
  99967. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99968. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99969. var frustumSlopeY = Math.tan(camera.fov / 2);
  99970. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99971. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99972. // along the forward vector.
  99973. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99974. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99975. };
  99976. /**
  99977. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99978. */
  99979. FramingBehavior.prototype._clearAnimationLocks = function () {
  99980. this._betaIsAnimating = false;
  99981. };
  99982. /**
  99983. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99984. */
  99985. FramingBehavior.prototype._applyUserInteraction = function () {
  99986. if (this.isUserIsMoving) {
  99987. this._lastInteractionTime = BABYLON.Tools.Now;
  99988. this.stopAllAnimations();
  99989. this._clearAnimationLocks();
  99990. }
  99991. };
  99992. /**
  99993. * Stops and removes all animations that have been applied to the camera
  99994. */
  99995. FramingBehavior.prototype.stopAllAnimations = function () {
  99996. if (this._attachedCamera) {
  99997. this._attachedCamera.animations = [];
  99998. }
  99999. while (this._animatables.length) {
  100000. if (this._animatables[0]) {
  100001. this._animatables[0].onAnimationEnd = null;
  100002. this._animatables[0].stop();
  100003. }
  100004. this._animatables.shift();
  100005. }
  100006. };
  100007. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100008. /**
  100009. * Gets a value indicating if the user is moving the camera
  100010. */
  100011. get: function () {
  100012. if (!this._attachedCamera) {
  100013. return false;
  100014. }
  100015. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100016. this._attachedCamera.inertialBetaOffset !== 0 ||
  100017. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100018. this._attachedCamera.inertialPanningX !== 0 ||
  100019. this._attachedCamera.inertialPanningY !== 0 ||
  100020. this._isPointerDown;
  100021. },
  100022. enumerable: true,
  100023. configurable: true
  100024. });
  100025. /**
  100026. * The easing function used by animations
  100027. */
  100028. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100029. /**
  100030. * The easing mode used by animations
  100031. */
  100032. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100033. // Statics
  100034. /**
  100035. * The camera can move all the way towards the mesh.
  100036. */
  100037. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100038. /**
  100039. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100040. */
  100041. FramingBehavior.FitFrustumSidesMode = 1;
  100042. return FramingBehavior;
  100043. }());
  100044. BABYLON.FramingBehavior = FramingBehavior;
  100045. })(BABYLON || (BABYLON = {}));
  100046. //# sourceMappingURL=babylon.framingBehavior.js.map
  100047. var BABYLON;
  100048. (function (BABYLON) {
  100049. /**
  100050. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100051. */
  100052. var BouncingBehavior = /** @class */ (function () {
  100053. function BouncingBehavior() {
  100054. /**
  100055. * The duration of the animation, in milliseconds
  100056. */
  100057. this.transitionDuration = 450;
  100058. /**
  100059. * Length of the distance animated by the transition when lower radius is reached
  100060. */
  100061. this.lowerRadiusTransitionRange = 2;
  100062. /**
  100063. * Length of the distance animated by the transition when upper radius is reached
  100064. */
  100065. this.upperRadiusTransitionRange = -2;
  100066. this._autoTransitionRange = false;
  100067. // Animations
  100068. this._radiusIsAnimating = false;
  100069. this._radiusBounceTransition = null;
  100070. this._animatables = new Array();
  100071. }
  100072. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100073. get: function () {
  100074. return "Bouncing";
  100075. },
  100076. enumerable: true,
  100077. configurable: true
  100078. });
  100079. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100080. /**
  100081. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100082. */
  100083. get: function () {
  100084. return this._autoTransitionRange;
  100085. },
  100086. /**
  100087. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100088. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100089. */
  100090. set: function (value) {
  100091. var _this = this;
  100092. if (this._autoTransitionRange === value) {
  100093. return;
  100094. }
  100095. this._autoTransitionRange = value;
  100096. var camera = this._attachedCamera;
  100097. if (!camera) {
  100098. return;
  100099. }
  100100. if (value) {
  100101. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100102. if (!mesh) {
  100103. return;
  100104. }
  100105. mesh.computeWorldMatrix(true);
  100106. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100107. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100108. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100109. });
  100110. }
  100111. else if (this._onMeshTargetChangedObserver) {
  100112. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100113. }
  100114. },
  100115. enumerable: true,
  100116. configurable: true
  100117. });
  100118. BouncingBehavior.prototype.init = function () {
  100119. // Do notihng
  100120. };
  100121. BouncingBehavior.prototype.attach = function (camera) {
  100122. var _this = this;
  100123. this._attachedCamera = camera;
  100124. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100125. if (!_this._attachedCamera) {
  100126. return;
  100127. }
  100128. // Add the bounce animation to the lower radius limit
  100129. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100130. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100131. }
  100132. // Add the bounce animation to the upper radius limit
  100133. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100134. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100135. }
  100136. });
  100137. };
  100138. BouncingBehavior.prototype.detach = function () {
  100139. if (!this._attachedCamera) {
  100140. return;
  100141. }
  100142. if (this._onAfterCheckInputsObserver) {
  100143. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100144. }
  100145. if (this._onMeshTargetChangedObserver) {
  100146. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100147. }
  100148. this._attachedCamera = null;
  100149. };
  100150. /**
  100151. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100152. * @param radiusLimit The limit to check against.
  100153. * @return Bool to indicate if at limit.
  100154. */
  100155. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100156. if (!this._attachedCamera) {
  100157. return false;
  100158. }
  100159. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100160. return true;
  100161. }
  100162. return false;
  100163. };
  100164. /**
  100165. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100166. * @param radiusDelta The delta by which to animate to. Can be negative.
  100167. */
  100168. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100169. var _this = this;
  100170. if (!this._attachedCamera) {
  100171. return;
  100172. }
  100173. if (!this._radiusBounceTransition) {
  100174. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100175. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100176. }
  100177. // Prevent zoom until bounce has completed
  100178. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100179. this._attachedCamera.wheelPrecision = Infinity;
  100180. this._attachedCamera.inertialRadiusOffset = 0;
  100181. // Animate to the radius limit
  100182. this.stopAllAnimations();
  100183. this._radiusIsAnimating = true;
  100184. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100185. if (animatable) {
  100186. this._animatables.push(animatable);
  100187. }
  100188. };
  100189. /**
  100190. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100191. */
  100192. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100193. this._radiusIsAnimating = false;
  100194. if (this._attachedCamera) {
  100195. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100196. }
  100197. };
  100198. /**
  100199. * Stops and removes all animations that have been applied to the camera
  100200. */
  100201. BouncingBehavior.prototype.stopAllAnimations = function () {
  100202. if (this._attachedCamera) {
  100203. this._attachedCamera.animations = [];
  100204. }
  100205. while (this._animatables.length) {
  100206. this._animatables[0].onAnimationEnd = null;
  100207. this._animatables[0].stop();
  100208. this._animatables.shift();
  100209. }
  100210. };
  100211. /**
  100212. * The easing function used by animations
  100213. */
  100214. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100215. /**
  100216. * The easing mode used by animations
  100217. */
  100218. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100219. return BouncingBehavior;
  100220. }());
  100221. BABYLON.BouncingBehavior = BouncingBehavior;
  100222. })(BABYLON || (BABYLON = {}));
  100223. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100224. var BABYLON;
  100225. (function (BABYLON) {
  100226. var AutoRotationBehavior = /** @class */ (function () {
  100227. function AutoRotationBehavior() {
  100228. this._zoomStopsAnimation = false;
  100229. this._idleRotationSpeed = 0.05;
  100230. this._idleRotationWaitTime = 2000;
  100231. this._idleRotationSpinupTime = 2000;
  100232. this._isPointerDown = false;
  100233. this._lastFrameTime = null;
  100234. this._lastInteractionTime = -Infinity;
  100235. this._cameraRotationSpeed = 0;
  100236. this._lastFrameRadius = 0;
  100237. }
  100238. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100239. get: function () {
  100240. return "AutoRotation";
  100241. },
  100242. enumerable: true,
  100243. configurable: true
  100244. });
  100245. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100246. /**
  100247. * Gets the flag that indicates if user zooming should stop animation.
  100248. */
  100249. get: function () {
  100250. return this._zoomStopsAnimation;
  100251. },
  100252. /**
  100253. * Sets the flag that indicates if user zooming should stop animation.
  100254. */
  100255. set: function (flag) {
  100256. this._zoomStopsAnimation = flag;
  100257. },
  100258. enumerable: true,
  100259. configurable: true
  100260. });
  100261. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100262. /**
  100263. * Gets the default speed at which the camera rotates around the model.
  100264. */
  100265. get: function () {
  100266. return this._idleRotationSpeed;
  100267. },
  100268. /**
  100269. * Sets the default speed at which the camera rotates around the model.
  100270. */
  100271. set: function (speed) {
  100272. this._idleRotationSpeed = speed;
  100273. },
  100274. enumerable: true,
  100275. configurable: true
  100276. });
  100277. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100278. /**
  100279. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100280. */
  100281. get: function () {
  100282. return this._idleRotationWaitTime;
  100283. },
  100284. /**
  100285. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100286. */
  100287. set: function (time) {
  100288. this._idleRotationWaitTime = time;
  100289. },
  100290. enumerable: true,
  100291. configurable: true
  100292. });
  100293. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100294. /**
  100295. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100296. */
  100297. get: function () {
  100298. return this._idleRotationSpinupTime;
  100299. },
  100300. /**
  100301. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100302. */
  100303. set: function (time) {
  100304. this._idleRotationSpinupTime = time;
  100305. },
  100306. enumerable: true,
  100307. configurable: true
  100308. });
  100309. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100310. /**
  100311. * Gets a value indicating if the camera is currently rotating because of this behavior
  100312. */
  100313. get: function () {
  100314. return Math.abs(this._cameraRotationSpeed) > 0;
  100315. },
  100316. enumerable: true,
  100317. configurable: true
  100318. });
  100319. AutoRotationBehavior.prototype.init = function () {
  100320. // Do notihng
  100321. };
  100322. AutoRotationBehavior.prototype.attach = function (camera) {
  100323. var _this = this;
  100324. this._attachedCamera = camera;
  100325. var scene = this._attachedCamera.getScene();
  100326. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100327. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100328. _this._isPointerDown = true;
  100329. return;
  100330. }
  100331. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100332. _this._isPointerDown = false;
  100333. }
  100334. });
  100335. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100336. var now = BABYLON.Tools.Now;
  100337. var dt = 0;
  100338. if (_this._lastFrameTime != null) {
  100339. dt = now - _this._lastFrameTime;
  100340. }
  100341. _this._lastFrameTime = now;
  100342. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100343. _this._applyUserInteraction();
  100344. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100345. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100346. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100347. // Step camera rotation by rotation speed
  100348. if (_this._attachedCamera) {
  100349. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100350. }
  100351. });
  100352. };
  100353. AutoRotationBehavior.prototype.detach = function () {
  100354. if (!this._attachedCamera) {
  100355. return;
  100356. }
  100357. var scene = this._attachedCamera.getScene();
  100358. if (this._onPrePointerObservableObserver) {
  100359. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100360. }
  100361. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100362. this._attachedCamera = null;
  100363. };
  100364. /**
  100365. * Returns true if user is scrolling.
  100366. * @return true if user is scrolling.
  100367. */
  100368. AutoRotationBehavior.prototype._userIsZooming = function () {
  100369. if (!this._attachedCamera) {
  100370. return false;
  100371. }
  100372. return this._attachedCamera.inertialRadiusOffset !== 0;
  100373. };
  100374. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100375. if (!this._attachedCamera) {
  100376. return false;
  100377. }
  100378. var zoomHasHitLimit = false;
  100379. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100380. zoomHasHitLimit = true;
  100381. }
  100382. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100383. this._lastFrameRadius = this._attachedCamera.radius;
  100384. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100385. };
  100386. /**
  100387. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100388. */
  100389. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100390. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100391. this._lastInteractionTime = BABYLON.Tools.Now;
  100392. }
  100393. };
  100394. // Tools
  100395. AutoRotationBehavior.prototype._userIsMoving = function () {
  100396. if (!this._attachedCamera) {
  100397. return false;
  100398. }
  100399. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100400. this._attachedCamera.inertialBetaOffset !== 0 ||
  100401. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100402. this._attachedCamera.inertialPanningX !== 0 ||
  100403. this._attachedCamera.inertialPanningY !== 0 ||
  100404. this._isPointerDown;
  100405. };
  100406. return AutoRotationBehavior;
  100407. }());
  100408. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100409. })(BABYLON || (BABYLON = {}));
  100410. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100411. var BABYLON;
  100412. (function (BABYLON) {
  100413. var NullEngineOptions = /** @class */ (function () {
  100414. function NullEngineOptions() {
  100415. this.renderWidth = 512;
  100416. this.renderHeight = 256;
  100417. this.textureSize = 512;
  100418. this.deterministicLockstep = false;
  100419. this.lockstepMaxSteps = 4;
  100420. }
  100421. return NullEngineOptions;
  100422. }());
  100423. BABYLON.NullEngineOptions = NullEngineOptions;
  100424. /**
  100425. * The null engine class provides support for headless version of babylon.js.
  100426. * This can be used in server side scenario or for testing purposes
  100427. */
  100428. var NullEngine = /** @class */ (function (_super) {
  100429. __extends(NullEngine, _super);
  100430. function NullEngine(options) {
  100431. if (options === void 0) { options = new NullEngineOptions(); }
  100432. var _this = _super.call(this, null) || this;
  100433. if (options.deterministicLockstep === undefined) {
  100434. options.deterministicLockstep = false;
  100435. }
  100436. if (options.lockstepMaxSteps === undefined) {
  100437. options.lockstepMaxSteps = 4;
  100438. }
  100439. _this._options = options;
  100440. // Init caps
  100441. // We consider we are on a webgl1 capable device
  100442. _this._caps = new BABYLON.EngineCapabilities();
  100443. _this._caps.maxTexturesImageUnits = 16;
  100444. _this._caps.maxVertexTextureImageUnits = 16;
  100445. _this._caps.maxTextureSize = 512;
  100446. _this._caps.maxCubemapTextureSize = 512;
  100447. _this._caps.maxRenderTextureSize = 512;
  100448. _this._caps.maxVertexAttribs = 16;
  100449. _this._caps.maxVaryingVectors = 16;
  100450. _this._caps.maxFragmentUniformVectors = 16;
  100451. _this._caps.maxVertexUniformVectors = 16;
  100452. // Extensions
  100453. _this._caps.standardDerivatives = false;
  100454. _this._caps.astc = null;
  100455. _this._caps.s3tc = null;
  100456. _this._caps.pvrtc = null;
  100457. _this._caps.etc1 = null;
  100458. _this._caps.etc2 = null;
  100459. _this._caps.textureAnisotropicFilterExtension = null;
  100460. _this._caps.maxAnisotropy = 0;
  100461. _this._caps.uintIndices = false;
  100462. _this._caps.fragmentDepthSupported = false;
  100463. _this._caps.highPrecisionShaderSupported = true;
  100464. _this._caps.colorBufferFloat = false;
  100465. _this._caps.textureFloat = false;
  100466. _this._caps.textureFloatLinearFiltering = false;
  100467. _this._caps.textureFloatRender = false;
  100468. _this._caps.textureHalfFloat = false;
  100469. _this._caps.textureHalfFloatLinearFiltering = false;
  100470. _this._caps.textureHalfFloatRender = false;
  100471. _this._caps.textureLOD = false;
  100472. _this._caps.drawBuffersExtension = false;
  100473. _this._caps.depthTextureExtension = false;
  100474. _this._caps.vertexArrayObject = false;
  100475. _this._caps.instancedArrays = false;
  100476. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100477. // Wrappers
  100478. if (typeof URL === "undefined") {
  100479. URL = {
  100480. createObjectURL: function () { },
  100481. revokeObjectURL: function () { }
  100482. };
  100483. }
  100484. if (typeof Blob === "undefined") {
  100485. Blob = function () { };
  100486. }
  100487. return _this;
  100488. }
  100489. NullEngine.prototype.isDeterministicLockStep = function () {
  100490. return this._options.deterministicLockstep;
  100491. };
  100492. NullEngine.prototype.getLockstepMaxSteps = function () {
  100493. return this._options.lockstepMaxSteps;
  100494. };
  100495. NullEngine.prototype.getHardwareScalingLevel = function () {
  100496. return 1.0;
  100497. };
  100498. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100499. return {
  100500. capacity: 0,
  100501. references: 1,
  100502. is32Bits: false
  100503. };
  100504. };
  100505. NullEngine.prototype.createIndexBuffer = function (indices) {
  100506. return {
  100507. capacity: 0,
  100508. references: 1,
  100509. is32Bits: false
  100510. };
  100511. };
  100512. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100513. if (stencil === void 0) { stencil = false; }
  100514. };
  100515. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100516. if (useScreen === void 0) { useScreen = false; }
  100517. if (!useScreen && this._currentRenderTarget) {
  100518. return this._currentRenderTarget.width;
  100519. }
  100520. return this._options.renderWidth;
  100521. };
  100522. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100523. if (useScreen === void 0) { useScreen = false; }
  100524. if (!useScreen && this._currentRenderTarget) {
  100525. return this._currentRenderTarget.height;
  100526. }
  100527. return this._options.renderHeight;
  100528. };
  100529. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100530. this._cachedViewport = viewport;
  100531. };
  100532. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100533. return {
  100534. transformFeedback: null,
  100535. __SPECTOR_rebuildProgram: null
  100536. };
  100537. };
  100538. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100539. return [];
  100540. };
  100541. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100542. return [];
  100543. };
  100544. NullEngine.prototype.bindSamplers = function (effect) {
  100545. this._currentEffect = null;
  100546. };
  100547. NullEngine.prototype.enableEffect = function (effect) {
  100548. this._currentEffect = effect;
  100549. if (effect.onBind) {
  100550. effect.onBind(effect);
  100551. }
  100552. effect.onBindObservable.notifyObservers(effect);
  100553. };
  100554. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100555. if (zOffset === void 0) { zOffset = 0; }
  100556. if (reverseSide === void 0) { reverseSide = false; }
  100557. };
  100558. NullEngine.prototype.setIntArray = function (uniform, array) {
  100559. };
  100560. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100561. };
  100562. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100563. };
  100564. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100565. };
  100566. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100567. };
  100568. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100569. };
  100570. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100571. };
  100572. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100573. };
  100574. NullEngine.prototype.setArray = function (uniform, array) {
  100575. };
  100576. NullEngine.prototype.setArray2 = function (uniform, array) {
  100577. };
  100578. NullEngine.prototype.setArray3 = function (uniform, array) {
  100579. };
  100580. NullEngine.prototype.setArray4 = function (uniform, array) {
  100581. };
  100582. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100583. };
  100584. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100585. };
  100586. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100587. };
  100588. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100589. };
  100590. NullEngine.prototype.setFloat = function (uniform, value) {
  100591. };
  100592. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100593. };
  100594. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100595. };
  100596. NullEngine.prototype.setBool = function (uniform, bool) {
  100597. };
  100598. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100599. };
  100600. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100601. };
  100602. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100603. };
  100604. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100605. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100606. if (this._alphaMode === mode) {
  100607. return;
  100608. }
  100609. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100610. if (!noDepthWriteChange) {
  100611. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100612. }
  100613. this._alphaMode = mode;
  100614. };
  100615. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100616. };
  100617. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100618. if (this.preventCacheWipeBetweenFrames) {
  100619. return;
  100620. }
  100621. this.resetTextureCache();
  100622. this._currentEffect = null;
  100623. if (bruteForce) {
  100624. this._currentProgram = null;
  100625. this._stencilState.reset();
  100626. this._depthCullingState.reset();
  100627. this._alphaState.reset();
  100628. }
  100629. this._cachedVertexBuffers = null;
  100630. this._cachedIndexBuffer = null;
  100631. this._cachedEffectForVertexBuffers = null;
  100632. };
  100633. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100634. };
  100635. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100636. };
  100637. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100638. };
  100639. NullEngine.prototype._createTexture = function () {
  100640. return {};
  100641. };
  100642. NullEngine.prototype._releaseTexture = function (texture) {
  100643. };
  100644. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100646. if (onLoad === void 0) { onLoad = null; }
  100647. if (onError === void 0) { onError = null; }
  100648. if (buffer === void 0) { buffer = null; }
  100649. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100650. var url = String(urlArg);
  100651. texture.url = url;
  100652. texture.generateMipMaps = !noMipmap;
  100653. texture.samplingMode = samplingMode;
  100654. texture.invertY = invertY;
  100655. texture.baseWidth = this._options.textureSize;
  100656. texture.baseHeight = this._options.textureSize;
  100657. texture.width = this._options.textureSize;
  100658. texture.height = this._options.textureSize;
  100659. if (format) {
  100660. texture.format = format;
  100661. }
  100662. texture.isReady = true;
  100663. if (onLoad) {
  100664. onLoad();
  100665. }
  100666. this._internalTexturesCache.push(texture);
  100667. return texture;
  100668. };
  100669. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100670. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100671. if (options !== undefined && typeof options === "object") {
  100672. fullOptions.generateMipMaps = options.generateMipMaps;
  100673. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100674. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100675. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100676. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100677. }
  100678. else {
  100679. fullOptions.generateMipMaps = options;
  100680. fullOptions.generateDepthBuffer = true;
  100681. fullOptions.generateStencilBuffer = false;
  100682. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100683. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100684. }
  100685. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100686. var width = size.width || size;
  100687. var height = size.height || size;
  100688. texture._depthStencilBuffer = {};
  100689. texture._framebuffer = {};
  100690. texture.baseWidth = width;
  100691. texture.baseHeight = height;
  100692. texture.width = width;
  100693. texture.height = height;
  100694. texture.isReady = true;
  100695. texture.samples = 1;
  100696. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100697. texture.samplingMode = fullOptions.samplingMode;
  100698. texture.type = fullOptions.type;
  100699. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100700. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100701. this._internalTexturesCache.push(texture);
  100702. return texture;
  100703. };
  100704. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100705. texture.samplingMode = samplingMode;
  100706. };
  100707. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100708. if (this._currentRenderTarget) {
  100709. this.unBindFramebuffer(this._currentRenderTarget);
  100710. }
  100711. this._currentRenderTarget = texture;
  100712. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100713. if (this._cachedViewport && !forceFullscreenViewport) {
  100714. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100715. }
  100716. };
  100717. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100718. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100719. this._currentRenderTarget = null;
  100720. if (onBeforeUnbind) {
  100721. if (texture._MSAAFramebuffer) {
  100722. this._currentFramebuffer = texture._framebuffer;
  100723. }
  100724. onBeforeUnbind();
  100725. }
  100726. this._currentFramebuffer = null;
  100727. };
  100728. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100729. var vbo = {
  100730. capacity: 1,
  100731. references: 1,
  100732. is32Bits: false
  100733. };
  100734. return vbo;
  100735. };
  100736. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100737. if (premulAlpha === void 0) { premulAlpha = false; }
  100738. };
  100739. /**
  100740. * Get the current error code of the webGL context
  100741. * @returns the error code
  100742. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  100743. */
  100744. NullEngine.prototype.getError = function () {
  100745. return 0;
  100746. };
  100747. /** @hidden */
  100748. NullEngine.prototype._getUnpackAlignement = function () {
  100749. return 1;
  100750. };
  100751. /** @hidden */
  100752. NullEngine.prototype._unpackFlipY = function (value) {
  100753. };
  100754. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100755. if (offset === void 0) { offset = 0; }
  100756. };
  100757. /**
  100758. * Updates a dynamic vertex buffer.
  100759. * @param vertexBuffer the vertex buffer to update
  100760. * @param data the data used to update the vertex buffer
  100761. * @param byteOffset the byte offset of the data (optional)
  100762. * @param byteLength the byte length of the data (optional)
  100763. */
  100764. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100765. };
  100766. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100767. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100768. this._boundTexturesCache[this._activeChannel] = texture;
  100769. return true;
  100770. }
  100771. return false;
  100772. };
  100773. NullEngine.prototype._bindTexture = function (channel, texture) {
  100774. if (channel < 0) {
  100775. return;
  100776. }
  100777. this._bindTextureDirectly(0, texture);
  100778. };
  100779. NullEngine.prototype._releaseBuffer = function (buffer) {
  100780. buffer.references--;
  100781. if (buffer.references === 0) {
  100782. return true;
  100783. }
  100784. return false;
  100785. };
  100786. NullEngine.prototype.releaseEffects = function () {
  100787. };
  100788. NullEngine.prototype.displayLoadingUI = function () {
  100789. };
  100790. NullEngine.prototype.hideLoadingUI = function () {
  100791. };
  100792. /** @hidden */
  100793. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  100794. if (faceIndex === void 0) { faceIndex = 0; }
  100795. if (lod === void 0) { lod = 0; }
  100796. };
  100797. /** @hidden */
  100798. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  100799. if (faceIndex === void 0) { faceIndex = 0; }
  100800. if (lod === void 0) { lod = 0; }
  100801. };
  100802. /** @hidden */
  100803. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  100804. if (faceIndex === void 0) { faceIndex = 0; }
  100805. if (lod === void 0) { lod = 0; }
  100806. };
  100807. /** @hidden */
  100808. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  100809. if (faceIndex === void 0) { faceIndex = 0; }
  100810. if (lod === void 0) { lod = 0; }
  100811. };
  100812. return NullEngine;
  100813. }(BABYLON.Engine));
  100814. BABYLON.NullEngine = NullEngine;
  100815. })(BABYLON || (BABYLON = {}));
  100816. //# sourceMappingURL=babylon.nullEngine.js.map
  100817. var BABYLON;
  100818. (function (BABYLON) {
  100819. /**
  100820. * This class can be used to get instrumentation data from a Babylon engine
  100821. */
  100822. var EngineInstrumentation = /** @class */ (function () {
  100823. function EngineInstrumentation(engine) {
  100824. this.engine = engine;
  100825. this._captureGPUFrameTime = false;
  100826. this._gpuFrameTime = new BABYLON.PerfCounter();
  100827. this._captureShaderCompilationTime = false;
  100828. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100829. // Observers
  100830. this._onBeginFrameObserver = null;
  100831. this._onEndFrameObserver = null;
  100832. this._onBeforeShaderCompilationObserver = null;
  100833. this._onAfterShaderCompilationObserver = null;
  100834. }
  100835. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100836. // Properties
  100837. /**
  100838. * Gets the perf counter used for GPU frame time
  100839. */
  100840. get: function () {
  100841. return this._gpuFrameTime;
  100842. },
  100843. enumerable: true,
  100844. configurable: true
  100845. });
  100846. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100847. /**
  100848. * Gets the GPU frame time capture status
  100849. */
  100850. get: function () {
  100851. return this._captureGPUFrameTime;
  100852. },
  100853. /**
  100854. * Enable or disable the GPU frame time capture
  100855. */
  100856. set: function (value) {
  100857. var _this = this;
  100858. if (value === this._captureGPUFrameTime) {
  100859. return;
  100860. }
  100861. this._captureGPUFrameTime = value;
  100862. if (value) {
  100863. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100864. if (!_this._gpuFrameTimeToken) {
  100865. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100866. }
  100867. });
  100868. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100869. if (!_this._gpuFrameTimeToken) {
  100870. return;
  100871. }
  100872. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100873. if (time > -1) {
  100874. _this._gpuFrameTimeToken = null;
  100875. _this._gpuFrameTime.fetchNewFrame();
  100876. _this._gpuFrameTime.addCount(time, true);
  100877. }
  100878. });
  100879. }
  100880. else {
  100881. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100882. this._onBeginFrameObserver = null;
  100883. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100884. this._onEndFrameObserver = null;
  100885. }
  100886. },
  100887. enumerable: true,
  100888. configurable: true
  100889. });
  100890. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100891. /**
  100892. * Gets the perf counter used for shader compilation time
  100893. */
  100894. get: function () {
  100895. return this._shaderCompilationTime;
  100896. },
  100897. enumerable: true,
  100898. configurable: true
  100899. });
  100900. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100901. /**
  100902. * Gets the shader compilation time capture status
  100903. */
  100904. get: function () {
  100905. return this._captureShaderCompilationTime;
  100906. },
  100907. /**
  100908. * Enable or disable the shader compilation time capture
  100909. */
  100910. set: function (value) {
  100911. var _this = this;
  100912. if (value === this._captureShaderCompilationTime) {
  100913. return;
  100914. }
  100915. this._captureShaderCompilationTime = value;
  100916. if (value) {
  100917. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100918. _this._shaderCompilationTime.fetchNewFrame();
  100919. _this._shaderCompilationTime.beginMonitoring();
  100920. });
  100921. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100922. _this._shaderCompilationTime.endMonitoring();
  100923. });
  100924. }
  100925. else {
  100926. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100927. this._onBeforeShaderCompilationObserver = null;
  100928. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100929. this._onAfterShaderCompilationObserver = null;
  100930. }
  100931. },
  100932. enumerable: true,
  100933. configurable: true
  100934. });
  100935. EngineInstrumentation.prototype.dispose = function () {
  100936. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100937. this._onBeginFrameObserver = null;
  100938. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100939. this._onEndFrameObserver = null;
  100940. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100941. this._onBeforeShaderCompilationObserver = null;
  100942. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100943. this._onAfterShaderCompilationObserver = null;
  100944. this.engine = null;
  100945. };
  100946. return EngineInstrumentation;
  100947. }());
  100948. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100949. })(BABYLON || (BABYLON = {}));
  100950. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100951. var BABYLON;
  100952. (function (BABYLON) {
  100953. /**
  100954. * This class can be used to get instrumentation data from a Babylon engine
  100955. */
  100956. var SceneInstrumentation = /** @class */ (function () {
  100957. function SceneInstrumentation(scene) {
  100958. var _this = this;
  100959. this.scene = scene;
  100960. this._captureActiveMeshesEvaluationTime = false;
  100961. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100962. this._captureRenderTargetsRenderTime = false;
  100963. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100964. this._captureFrameTime = false;
  100965. this._frameTime = new BABYLON.PerfCounter();
  100966. this._captureRenderTime = false;
  100967. this._renderTime = new BABYLON.PerfCounter();
  100968. this._captureInterFrameTime = false;
  100969. this._interFrameTime = new BABYLON.PerfCounter();
  100970. this._captureParticlesRenderTime = false;
  100971. this._particlesRenderTime = new BABYLON.PerfCounter();
  100972. this._captureSpritesRenderTime = false;
  100973. this._spritesRenderTime = new BABYLON.PerfCounter();
  100974. this._capturePhysicsTime = false;
  100975. this._physicsTime = new BABYLON.PerfCounter();
  100976. this._captureAnimationsTime = false;
  100977. this._animationsTime = new BABYLON.PerfCounter();
  100978. this._captureCameraRenderTime = false;
  100979. this._cameraRenderTime = new BABYLON.PerfCounter();
  100980. // Observers
  100981. this._onBeforeActiveMeshesEvaluationObserver = null;
  100982. this._onAfterActiveMeshesEvaluationObserver = null;
  100983. this._onBeforeRenderTargetsRenderObserver = null;
  100984. this._onAfterRenderTargetsRenderObserver = null;
  100985. this._onAfterRenderObserver = null;
  100986. this._onBeforeDrawPhaseObserver = null;
  100987. this._onAfterDrawPhaseObserver = null;
  100988. this._onBeforeAnimationsObserver = null;
  100989. this._onBeforeParticlesRenderingObserver = null;
  100990. this._onAfterParticlesRenderingObserver = null;
  100991. this._onBeforeSpritesRenderingObserver = null;
  100992. this._onAfterSpritesRenderingObserver = null;
  100993. this._onBeforePhysicsObserver = null;
  100994. this._onAfterPhysicsObserver = null;
  100995. this._onAfterAnimationsObserver = null;
  100996. this._onBeforeCameraRenderObserver = null;
  100997. this._onAfterCameraRenderObserver = null;
  100998. // Before render
  100999. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101000. if (_this._captureActiveMeshesEvaluationTime) {
  101001. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101002. }
  101003. if (_this._captureRenderTargetsRenderTime) {
  101004. _this._renderTargetsRenderTime.fetchNewFrame();
  101005. }
  101006. if (_this._captureFrameTime) {
  101007. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101008. _this._frameTime.beginMonitoring();
  101009. }
  101010. if (_this._captureInterFrameTime) {
  101011. _this._interFrameTime.endMonitoring();
  101012. }
  101013. if (_this._captureParticlesRenderTime) {
  101014. _this._particlesRenderTime.fetchNewFrame();
  101015. }
  101016. if (_this._captureSpritesRenderTime) {
  101017. _this._spritesRenderTime.fetchNewFrame();
  101018. }
  101019. if (_this._captureAnimationsTime) {
  101020. _this._animationsTime.beginMonitoring();
  101021. }
  101022. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101023. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101024. });
  101025. // After render
  101026. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101027. if (_this._captureFrameTime) {
  101028. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101029. _this._frameTime.endMonitoring();
  101030. }
  101031. if (_this._captureRenderTime) {
  101032. _this._renderTime.endMonitoring(false);
  101033. }
  101034. if (_this._captureInterFrameTime) {
  101035. _this._interFrameTime.beginMonitoring();
  101036. }
  101037. });
  101038. }
  101039. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101040. // Properties
  101041. /**
  101042. * Gets the perf counter used for active meshes evaluation time
  101043. */
  101044. get: function () {
  101045. return this._activeMeshesEvaluationTime;
  101046. },
  101047. enumerable: true,
  101048. configurable: true
  101049. });
  101050. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101051. /**
  101052. * Gets the active meshes evaluation time capture status
  101053. */
  101054. get: function () {
  101055. return this._captureActiveMeshesEvaluationTime;
  101056. },
  101057. /**
  101058. * Enable or disable the active meshes evaluation time capture
  101059. */
  101060. set: function (value) {
  101061. var _this = this;
  101062. if (value === this._captureActiveMeshesEvaluationTime) {
  101063. return;
  101064. }
  101065. this._captureActiveMeshesEvaluationTime = value;
  101066. if (value) {
  101067. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101068. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101069. _this._activeMeshesEvaluationTime.beginMonitoring();
  101070. });
  101071. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101072. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101073. _this._activeMeshesEvaluationTime.endMonitoring();
  101074. });
  101075. }
  101076. else {
  101077. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101078. this._onBeforeActiveMeshesEvaluationObserver = null;
  101079. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101080. this._onAfterActiveMeshesEvaluationObserver = null;
  101081. }
  101082. },
  101083. enumerable: true,
  101084. configurable: true
  101085. });
  101086. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101087. /**
  101088. * Gets the perf counter used for render targets render time
  101089. */
  101090. get: function () {
  101091. return this._renderTargetsRenderTime;
  101092. },
  101093. enumerable: true,
  101094. configurable: true
  101095. });
  101096. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101097. /**
  101098. * Gets the render targets render time capture status
  101099. */
  101100. get: function () {
  101101. return this._captureRenderTargetsRenderTime;
  101102. },
  101103. /**
  101104. * Enable or disable the render targets render time capture
  101105. */
  101106. set: function (value) {
  101107. var _this = this;
  101108. if (value === this._captureRenderTargetsRenderTime) {
  101109. return;
  101110. }
  101111. this._captureRenderTargetsRenderTime = value;
  101112. if (value) {
  101113. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101114. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101115. _this._renderTargetsRenderTime.beginMonitoring();
  101116. });
  101117. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101118. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101119. _this._renderTargetsRenderTime.endMonitoring(false);
  101120. });
  101121. }
  101122. else {
  101123. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101124. this._onBeforeRenderTargetsRenderObserver = null;
  101125. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101126. this._onAfterRenderTargetsRenderObserver = null;
  101127. }
  101128. },
  101129. enumerable: true,
  101130. configurable: true
  101131. });
  101132. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101133. /**
  101134. * Gets the perf counter used for particles render time
  101135. */
  101136. get: function () {
  101137. return this._particlesRenderTime;
  101138. },
  101139. enumerable: true,
  101140. configurable: true
  101141. });
  101142. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101143. /**
  101144. * Gets the particles render time capture status
  101145. */
  101146. get: function () {
  101147. return this._captureParticlesRenderTime;
  101148. },
  101149. /**
  101150. * Enable or disable the particles render time capture
  101151. */
  101152. set: function (value) {
  101153. var _this = this;
  101154. if (value === this._captureParticlesRenderTime) {
  101155. return;
  101156. }
  101157. this._captureParticlesRenderTime = value;
  101158. if (value) {
  101159. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101160. BABYLON.Tools.StartPerformanceCounter("Particles");
  101161. _this._particlesRenderTime.beginMonitoring();
  101162. });
  101163. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101164. BABYLON.Tools.EndPerformanceCounter("Particles");
  101165. _this._particlesRenderTime.endMonitoring(false);
  101166. });
  101167. }
  101168. else {
  101169. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101170. this._onBeforeParticlesRenderingObserver = null;
  101171. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101172. this._onAfterParticlesRenderingObserver = null;
  101173. }
  101174. },
  101175. enumerable: true,
  101176. configurable: true
  101177. });
  101178. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101179. /**
  101180. * Gets the perf counter used for sprites render time
  101181. */
  101182. get: function () {
  101183. return this._spritesRenderTime;
  101184. },
  101185. enumerable: true,
  101186. configurable: true
  101187. });
  101188. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101189. /**
  101190. * Gets the sprites render time capture status
  101191. */
  101192. get: function () {
  101193. return this._captureSpritesRenderTime;
  101194. },
  101195. /**
  101196. * Enable or disable the sprites render time capture
  101197. */
  101198. set: function (value) {
  101199. var _this = this;
  101200. if (value === this._captureSpritesRenderTime) {
  101201. return;
  101202. }
  101203. this._captureSpritesRenderTime = value;
  101204. if (value) {
  101205. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101206. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101207. _this._spritesRenderTime.beginMonitoring();
  101208. });
  101209. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101210. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101211. _this._spritesRenderTime.endMonitoring(false);
  101212. });
  101213. }
  101214. else {
  101215. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101216. this._onBeforeSpritesRenderingObserver = null;
  101217. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101218. this._onAfterSpritesRenderingObserver = null;
  101219. }
  101220. },
  101221. enumerable: true,
  101222. configurable: true
  101223. });
  101224. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101225. /**
  101226. * Gets the perf counter used for physics time
  101227. */
  101228. get: function () {
  101229. return this._physicsTime;
  101230. },
  101231. enumerable: true,
  101232. configurable: true
  101233. });
  101234. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101235. /**
  101236. * Gets the physics time capture status
  101237. */
  101238. get: function () {
  101239. return this._capturePhysicsTime;
  101240. },
  101241. /**
  101242. * Enable or disable the physics time capture
  101243. */
  101244. set: function (value) {
  101245. var _this = this;
  101246. if (value === this._capturePhysicsTime) {
  101247. return;
  101248. }
  101249. this._capturePhysicsTime = value;
  101250. if (value) {
  101251. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101252. BABYLON.Tools.StartPerformanceCounter("Physics");
  101253. _this._physicsTime.beginMonitoring();
  101254. });
  101255. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101256. BABYLON.Tools.EndPerformanceCounter("Physics");
  101257. _this._physicsTime.endMonitoring();
  101258. });
  101259. }
  101260. else {
  101261. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101262. this._onBeforePhysicsObserver = null;
  101263. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101264. this._onAfterPhysicsObserver = null;
  101265. }
  101266. },
  101267. enumerable: true,
  101268. configurable: true
  101269. });
  101270. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101271. /**
  101272. * Gets the perf counter used for animations time
  101273. */
  101274. get: function () {
  101275. return this._animationsTime;
  101276. },
  101277. enumerable: true,
  101278. configurable: true
  101279. });
  101280. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101281. /**
  101282. * Gets the animations time capture status
  101283. */
  101284. get: function () {
  101285. return this._captureAnimationsTime;
  101286. },
  101287. /**
  101288. * Enable or disable the animations time capture
  101289. */
  101290. set: function (value) {
  101291. var _this = this;
  101292. if (value === this._captureAnimationsTime) {
  101293. return;
  101294. }
  101295. this._captureAnimationsTime = value;
  101296. if (value) {
  101297. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101298. _this._animationsTime.endMonitoring();
  101299. });
  101300. }
  101301. else {
  101302. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101303. this._onAfterAnimationsObserver = null;
  101304. }
  101305. },
  101306. enumerable: true,
  101307. configurable: true
  101308. });
  101309. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101310. /**
  101311. * Gets the perf counter used for frame time capture
  101312. */
  101313. get: function () {
  101314. return this._frameTime;
  101315. },
  101316. enumerable: true,
  101317. configurable: true
  101318. });
  101319. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101320. /**
  101321. * Gets the frame time capture status
  101322. */
  101323. get: function () {
  101324. return this._captureFrameTime;
  101325. },
  101326. /**
  101327. * Enable or disable the frame time capture
  101328. */
  101329. set: function (value) {
  101330. this._captureFrameTime = value;
  101331. },
  101332. enumerable: true,
  101333. configurable: true
  101334. });
  101335. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101336. /**
  101337. * Gets the perf counter used for inter-frames time capture
  101338. */
  101339. get: function () {
  101340. return this._interFrameTime;
  101341. },
  101342. enumerable: true,
  101343. configurable: true
  101344. });
  101345. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101346. /**
  101347. * Gets the inter-frames time capture status
  101348. */
  101349. get: function () {
  101350. return this._captureInterFrameTime;
  101351. },
  101352. /**
  101353. * Enable or disable the inter-frames time capture
  101354. */
  101355. set: function (value) {
  101356. this._captureInterFrameTime = value;
  101357. },
  101358. enumerable: true,
  101359. configurable: true
  101360. });
  101361. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101362. /**
  101363. * Gets the perf counter used for render time capture
  101364. */
  101365. get: function () {
  101366. return this._renderTime;
  101367. },
  101368. enumerable: true,
  101369. configurable: true
  101370. });
  101371. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101372. /**
  101373. * Gets the render time capture status
  101374. */
  101375. get: function () {
  101376. return this._captureRenderTime;
  101377. },
  101378. /**
  101379. * Enable or disable the render time capture
  101380. */
  101381. set: function (value) {
  101382. var _this = this;
  101383. if (value === this._captureRenderTime) {
  101384. return;
  101385. }
  101386. this._captureRenderTime = value;
  101387. if (value) {
  101388. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101389. _this._renderTime.beginMonitoring();
  101390. BABYLON.Tools.StartPerformanceCounter("Main render");
  101391. });
  101392. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101393. _this._renderTime.endMonitoring(false);
  101394. BABYLON.Tools.EndPerformanceCounter("Main render");
  101395. });
  101396. }
  101397. else {
  101398. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101399. this._onBeforeDrawPhaseObserver = null;
  101400. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101401. this._onAfterDrawPhaseObserver = null;
  101402. }
  101403. },
  101404. enumerable: true,
  101405. configurable: true
  101406. });
  101407. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101408. /**
  101409. * Gets the perf counter used for camera render time capture
  101410. */
  101411. get: function () {
  101412. return this._cameraRenderTime;
  101413. },
  101414. enumerable: true,
  101415. configurable: true
  101416. });
  101417. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101418. /**
  101419. * Gets the camera render time capture status
  101420. */
  101421. get: function () {
  101422. return this._captureCameraRenderTime;
  101423. },
  101424. /**
  101425. * Enable or disable the camera render time capture
  101426. */
  101427. set: function (value) {
  101428. var _this = this;
  101429. if (value === this._captureCameraRenderTime) {
  101430. return;
  101431. }
  101432. this._captureCameraRenderTime = value;
  101433. if (value) {
  101434. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101435. _this._cameraRenderTime.beginMonitoring();
  101436. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101437. });
  101438. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101439. _this._cameraRenderTime.endMonitoring(false);
  101440. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101441. });
  101442. }
  101443. else {
  101444. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101445. this._onBeforeCameraRenderObserver = null;
  101446. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101447. this._onAfterCameraRenderObserver = null;
  101448. }
  101449. },
  101450. enumerable: true,
  101451. configurable: true
  101452. });
  101453. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101454. /**
  101455. * Gets the perf counter used for draw calls
  101456. */
  101457. get: function () {
  101458. return this.scene.getEngine()._drawCalls;
  101459. },
  101460. enumerable: true,
  101461. configurable: true
  101462. });
  101463. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101464. /**
  101465. * Gets the perf counter used for texture collisions
  101466. */
  101467. get: function () {
  101468. return this.scene.getEngine()._textureCollisions;
  101469. },
  101470. enumerable: true,
  101471. configurable: true
  101472. });
  101473. SceneInstrumentation.prototype.dispose = function () {
  101474. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101475. this._onAfterRenderObserver = null;
  101476. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101477. this._onBeforeActiveMeshesEvaluationObserver = null;
  101478. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101479. this._onAfterActiveMeshesEvaluationObserver = null;
  101480. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101481. this._onBeforeRenderTargetsRenderObserver = null;
  101482. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101483. this._onAfterRenderTargetsRenderObserver = null;
  101484. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101485. this._onBeforeAnimationsObserver = null;
  101486. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101487. this._onBeforeParticlesRenderingObserver = null;
  101488. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101489. this._onAfterParticlesRenderingObserver = null;
  101490. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101491. this._onBeforeSpritesRenderingObserver = null;
  101492. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101493. this._onAfterSpritesRenderingObserver = null;
  101494. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101495. this._onBeforeDrawPhaseObserver = null;
  101496. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101497. this._onAfterDrawPhaseObserver = null;
  101498. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101499. this._onBeforePhysicsObserver = null;
  101500. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101501. this._onAfterPhysicsObserver = null;
  101502. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101503. this._onAfterAnimationsObserver = null;
  101504. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101505. this._onBeforeCameraRenderObserver = null;
  101506. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101507. this._onAfterCameraRenderObserver = null;
  101508. this.scene = null;
  101509. };
  101510. return SceneInstrumentation;
  101511. }());
  101512. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101513. })(BABYLON || (BABYLON = {}));
  101514. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101515. var BABYLON;
  101516. (function (BABYLON) {
  101517. /**
  101518. * @hidden
  101519. **/
  101520. var _TimeToken = /** @class */ (function () {
  101521. function _TimeToken() {
  101522. this._timeElapsedQueryEnded = false;
  101523. }
  101524. return _TimeToken;
  101525. }());
  101526. BABYLON._TimeToken = _TimeToken;
  101527. })(BABYLON || (BABYLON = {}));
  101528. //# sourceMappingURL=babylon.timeToken.js.map
  101529. var BABYLON;
  101530. (function (BABYLON) {
  101531. /**
  101532. * Background material defines definition.
  101533. * @hidden Mainly internal Use
  101534. */
  101535. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101536. __extends(BackgroundMaterialDefines, _super);
  101537. /**
  101538. * Constructor of the defines.
  101539. */
  101540. function BackgroundMaterialDefines() {
  101541. var _this = _super.call(this) || this;
  101542. /**
  101543. * True if the diffuse texture is in use.
  101544. */
  101545. _this.DIFFUSE = false;
  101546. /**
  101547. * The direct UV channel to use.
  101548. */
  101549. _this.DIFFUSEDIRECTUV = 0;
  101550. /**
  101551. * True if the diffuse texture is in gamma space.
  101552. */
  101553. _this.GAMMADIFFUSE = false;
  101554. /**
  101555. * True if the diffuse texture has opacity in the alpha channel.
  101556. */
  101557. _this.DIFFUSEHASALPHA = false;
  101558. /**
  101559. * True if you want the material to fade to transparent at grazing angle.
  101560. */
  101561. _this.OPACITYFRESNEL = false;
  101562. /**
  101563. * True if an extra blur needs to be added in the reflection.
  101564. */
  101565. _this.REFLECTIONBLUR = false;
  101566. /**
  101567. * True if you want the material to fade to reflection at grazing angle.
  101568. */
  101569. _this.REFLECTIONFRESNEL = false;
  101570. /**
  101571. * True if you want the material to falloff as far as you move away from the scene center.
  101572. */
  101573. _this.REFLECTIONFALLOFF = false;
  101574. /**
  101575. * False if the current Webgl implementation does not support the texture lod extension.
  101576. */
  101577. _this.TEXTURELODSUPPORT = false;
  101578. /**
  101579. * True to ensure the data are premultiplied.
  101580. */
  101581. _this.PREMULTIPLYALPHA = false;
  101582. /**
  101583. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101584. */
  101585. _this.USERGBCOLOR = false;
  101586. /**
  101587. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101588. * stays aligned with the desired configuration.
  101589. */
  101590. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101591. /**
  101592. * True to add noise in order to reduce the banding effect.
  101593. */
  101594. _this.NOISE = false;
  101595. /**
  101596. * is the reflection texture in BGR color scheme?
  101597. * Mainly used to solve a bug in ios10 video tag
  101598. */
  101599. _this.REFLECTIONBGR = false;
  101600. _this.IMAGEPROCESSING = false;
  101601. _this.VIGNETTE = false;
  101602. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101603. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101604. _this.TONEMAPPING = false;
  101605. _this.CONTRAST = false;
  101606. _this.COLORCURVES = false;
  101607. _this.COLORGRADING = false;
  101608. _this.COLORGRADING3D = false;
  101609. _this.SAMPLER3DGREENDEPTH = false;
  101610. _this.SAMPLER3DBGRMAP = false;
  101611. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101612. _this.EXPOSURE = false;
  101613. // Reflection.
  101614. _this.REFLECTION = false;
  101615. _this.REFLECTIONMAP_3D = false;
  101616. _this.REFLECTIONMAP_SPHERICAL = false;
  101617. _this.REFLECTIONMAP_PLANAR = false;
  101618. _this.REFLECTIONMAP_CUBIC = false;
  101619. _this.REFLECTIONMAP_PROJECTION = false;
  101620. _this.REFLECTIONMAP_SKYBOX = false;
  101621. _this.REFLECTIONMAP_EXPLICIT = false;
  101622. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101623. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101624. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101625. _this.INVERTCUBICMAP = false;
  101626. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101627. _this.LODINREFLECTIONALPHA = false;
  101628. _this.GAMMAREFLECTION = false;
  101629. _this.RGBDREFLECTION = false;
  101630. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101631. // Default BJS.
  101632. _this.MAINUV1 = false;
  101633. _this.MAINUV2 = false;
  101634. _this.UV1 = false;
  101635. _this.UV2 = false;
  101636. _this.CLIPPLANE = false;
  101637. _this.POINTSIZE = false;
  101638. _this.FOG = false;
  101639. _this.NORMAL = false;
  101640. _this.NUM_BONE_INFLUENCERS = 0;
  101641. _this.BonesPerMesh = 0;
  101642. _this.INSTANCES = false;
  101643. _this.SHADOWFLOAT = false;
  101644. _this.rebuild();
  101645. return _this;
  101646. }
  101647. return BackgroundMaterialDefines;
  101648. }(BABYLON.MaterialDefines));
  101649. /**
  101650. * Background material used to create an efficient environement around your scene.
  101651. */
  101652. var BackgroundMaterial = /** @class */ (function (_super) {
  101653. __extends(BackgroundMaterial, _super);
  101654. /**
  101655. * Instantiates a Background Material in the given scene
  101656. * @param name The friendly name of the material
  101657. * @param scene The scene to add the material to
  101658. */
  101659. function BackgroundMaterial(name, scene) {
  101660. var _this = _super.call(this, name, scene) || this;
  101661. /**
  101662. * Key light Color (multiply against the environement texture)
  101663. */
  101664. _this.primaryColor = BABYLON.Color3.White();
  101665. _this._primaryColorShadowLevel = 0;
  101666. _this._primaryColorHighlightLevel = 0;
  101667. /**
  101668. * Reflection Texture used in the material.
  101669. * Should be author in a specific way for the best result (refer to the documentation).
  101670. */
  101671. _this.reflectionTexture = null;
  101672. /**
  101673. * Reflection Texture level of blur.
  101674. *
  101675. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101676. * texture twice.
  101677. */
  101678. _this.reflectionBlur = 0;
  101679. /**
  101680. * Diffuse Texture used in the material.
  101681. * Should be author in a specific way for the best result (refer to the documentation).
  101682. */
  101683. _this.diffuseTexture = null;
  101684. _this._shadowLights = null;
  101685. /**
  101686. * Specify the list of lights casting shadow on the material.
  101687. * All scene shadow lights will be included if null.
  101688. */
  101689. _this.shadowLights = null;
  101690. /**
  101691. * Helps adjusting the shadow to a softer level if required.
  101692. * 0 means black shadows and 1 means no shadows.
  101693. */
  101694. _this.shadowLevel = 0;
  101695. /**
  101696. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101697. * It is usually zero but might be interesting to modify according to your setup.
  101698. */
  101699. _this.sceneCenter = BABYLON.Vector3.Zero();
  101700. /**
  101701. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101702. * This helps ensuring a nice transition when the camera goes under the ground.
  101703. */
  101704. _this.opacityFresnel = true;
  101705. /**
  101706. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101707. * This helps adding a mirror texture on the ground.
  101708. */
  101709. _this.reflectionFresnel = false;
  101710. /**
  101711. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101712. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101713. */
  101714. _this.reflectionFalloffDistance = 0.0;
  101715. /**
  101716. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101717. */
  101718. _this.reflectionAmount = 1.0;
  101719. /**
  101720. * This specifies the weight of the reflection at grazing angle.
  101721. */
  101722. _this.reflectionReflectance0 = 0.05;
  101723. /**
  101724. * This specifies the weight of the reflection at a perpendicular point of view.
  101725. */
  101726. _this.reflectionReflectance90 = 0.5;
  101727. /**
  101728. * Helps to directly use the maps channels instead of their level.
  101729. */
  101730. _this.useRGBColor = true;
  101731. /**
  101732. * This helps reducing the banding effect that could occur on the background.
  101733. */
  101734. _this.enableNoise = false;
  101735. _this._fovMultiplier = 1.0;
  101736. /**
  101737. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101738. */
  101739. _this.useEquirectangularFOV = false;
  101740. _this._maxSimultaneousLights = 4;
  101741. /**
  101742. * Number of Simultaneous lights allowed on the material.
  101743. */
  101744. _this.maxSimultaneousLights = 4;
  101745. /**
  101746. * Keep track of the image processing observer to allow dispose and replace.
  101747. */
  101748. _this._imageProcessingObserver = null;
  101749. /**
  101750. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101751. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101752. */
  101753. _this.switchToBGR = false;
  101754. // Temp values kept as cache in the material.
  101755. _this._renderTargets = new BABYLON.SmartArray(16);
  101756. _this._reflectionControls = BABYLON.Vector4.Zero();
  101757. _this._white = BABYLON.Color3.White();
  101758. _this._primaryShadowColor = BABYLON.Color3.Black();
  101759. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101760. // Setup the default processing configuration to the scene.
  101761. _this._attachImageProcessingConfiguration(null);
  101762. _this.getRenderTargetTextures = function () {
  101763. _this._renderTargets.reset();
  101764. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101765. _this._renderTargets.push(_this._diffuseTexture);
  101766. }
  101767. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101768. _this._renderTargets.push(_this._reflectionTexture);
  101769. }
  101770. return _this._renderTargets;
  101771. };
  101772. return _this;
  101773. }
  101774. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101775. /**
  101776. * Experimental Internal Use Only.
  101777. *
  101778. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101779. * This acts as a helper to set the primary color to a more "human friendly" value.
  101780. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101781. * output color as close as possible from the chosen value.
  101782. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101783. * part of lighting setup.)
  101784. */
  101785. get: function () {
  101786. return this.__perceptualColor;
  101787. },
  101788. set: function (value) {
  101789. this.__perceptualColor = value;
  101790. this._computePrimaryColorFromPerceptualColor();
  101791. this._markAllSubMeshesAsLightsDirty();
  101792. },
  101793. enumerable: true,
  101794. configurable: true
  101795. });
  101796. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101797. /**
  101798. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101799. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101800. */
  101801. get: function () {
  101802. return this._primaryColorShadowLevel;
  101803. },
  101804. set: function (value) {
  101805. this._primaryColorShadowLevel = value;
  101806. this._computePrimaryColors();
  101807. this._markAllSubMeshesAsLightsDirty();
  101808. },
  101809. enumerable: true,
  101810. configurable: true
  101811. });
  101812. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101813. /**
  101814. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101815. * The primary color is used at the level chosen to define what the white area would look.
  101816. */
  101817. get: function () {
  101818. return this._primaryColorHighlightLevel;
  101819. },
  101820. set: function (value) {
  101821. this._primaryColorHighlightLevel = value;
  101822. this._computePrimaryColors();
  101823. this._markAllSubMeshesAsLightsDirty();
  101824. },
  101825. enumerable: true,
  101826. configurable: true
  101827. });
  101828. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101829. /**
  101830. * Sets the reflection reflectance fresnel values according to the default standard
  101831. * empirically know to work well :-)
  101832. */
  101833. set: function (value) {
  101834. var reflectionWeight = value;
  101835. if (reflectionWeight < 0.5) {
  101836. reflectionWeight = reflectionWeight * 2.0;
  101837. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101838. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101839. }
  101840. else {
  101841. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101842. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101843. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101844. }
  101845. },
  101846. enumerable: true,
  101847. configurable: true
  101848. });
  101849. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101850. /**
  101851. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101852. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101853. * Recommended to be keep at 1.0 except for special cases.
  101854. */
  101855. get: function () {
  101856. return this._fovMultiplier;
  101857. },
  101858. set: function (value) {
  101859. if (isNaN(value)) {
  101860. value = 1.0;
  101861. }
  101862. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101863. },
  101864. enumerable: true,
  101865. configurable: true
  101866. });
  101867. /**
  101868. * Attaches a new image processing configuration to the PBR Material.
  101869. * @param configuration (if null the scene configuration will be use)
  101870. */
  101871. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101872. var _this = this;
  101873. if (configuration === this._imageProcessingConfiguration) {
  101874. return;
  101875. }
  101876. // Detaches observer.
  101877. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101878. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101879. }
  101880. // Pick the scene configuration if needed.
  101881. if (!configuration) {
  101882. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101883. }
  101884. else {
  101885. this._imageProcessingConfiguration = configuration;
  101886. }
  101887. // Attaches observer.
  101888. if (this._imageProcessingConfiguration) {
  101889. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101890. _this._computePrimaryColorFromPerceptualColor();
  101891. _this._markAllSubMeshesAsImageProcessingDirty();
  101892. });
  101893. }
  101894. };
  101895. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101896. /**
  101897. * Gets the image processing configuration used either in this material.
  101898. */
  101899. get: function () {
  101900. return this._imageProcessingConfiguration;
  101901. },
  101902. /**
  101903. * Sets the Default image processing configuration used either in the this material.
  101904. *
  101905. * If sets to null, the scene one is in use.
  101906. */
  101907. set: function (value) {
  101908. this._attachImageProcessingConfiguration(value);
  101909. // Ensure the effect will be rebuilt.
  101910. this._markAllSubMeshesAsTexturesDirty();
  101911. },
  101912. enumerable: true,
  101913. configurable: true
  101914. });
  101915. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101916. /**
  101917. * Gets wether the color curves effect is enabled.
  101918. */
  101919. get: function () {
  101920. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101921. },
  101922. /**
  101923. * Sets wether the color curves effect is enabled.
  101924. */
  101925. set: function (value) {
  101926. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101927. },
  101928. enumerable: true,
  101929. configurable: true
  101930. });
  101931. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101932. /**
  101933. * Gets wether the color grading effect is enabled.
  101934. */
  101935. get: function () {
  101936. return this.imageProcessingConfiguration.colorGradingEnabled;
  101937. },
  101938. /**
  101939. * Gets wether the color grading effect is enabled.
  101940. */
  101941. set: function (value) {
  101942. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101943. },
  101944. enumerable: true,
  101945. configurable: true
  101946. });
  101947. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101948. /**
  101949. * Gets wether tonemapping is enabled or not.
  101950. */
  101951. get: function () {
  101952. return this._imageProcessingConfiguration.toneMappingEnabled;
  101953. },
  101954. /**
  101955. * Sets wether tonemapping is enabled or not
  101956. */
  101957. set: function (value) {
  101958. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101959. },
  101960. enumerable: true,
  101961. configurable: true
  101962. });
  101963. ;
  101964. ;
  101965. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101966. /**
  101967. * The camera exposure used on this material.
  101968. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101969. * This corresponds to a photographic exposure.
  101970. */
  101971. get: function () {
  101972. return this._imageProcessingConfiguration.exposure;
  101973. },
  101974. /**
  101975. * The camera exposure used on this material.
  101976. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101977. * This corresponds to a photographic exposure.
  101978. */
  101979. set: function (value) {
  101980. this._imageProcessingConfiguration.exposure = value;
  101981. },
  101982. enumerable: true,
  101983. configurable: true
  101984. });
  101985. ;
  101986. ;
  101987. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101988. /**
  101989. * Gets The camera contrast used on this material.
  101990. */
  101991. get: function () {
  101992. return this._imageProcessingConfiguration.contrast;
  101993. },
  101994. /**
  101995. * Sets The camera contrast used on this material.
  101996. */
  101997. set: function (value) {
  101998. this._imageProcessingConfiguration.contrast = value;
  101999. },
  102000. enumerable: true,
  102001. configurable: true
  102002. });
  102003. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102004. /**
  102005. * Gets the Color Grading 2D Lookup Texture.
  102006. */
  102007. get: function () {
  102008. return this._imageProcessingConfiguration.colorGradingTexture;
  102009. },
  102010. /**
  102011. * Sets the Color Grading 2D Lookup Texture.
  102012. */
  102013. set: function (value) {
  102014. this.imageProcessingConfiguration.colorGradingTexture = value;
  102015. },
  102016. enumerable: true,
  102017. configurable: true
  102018. });
  102019. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102020. /**
  102021. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102022. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102023. * 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;
  102024. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102025. */
  102026. get: function () {
  102027. return this.imageProcessingConfiguration.colorCurves;
  102028. },
  102029. /**
  102030. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102031. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102032. * 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;
  102033. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102034. */
  102035. set: function (value) {
  102036. this.imageProcessingConfiguration.colorCurves = value;
  102037. },
  102038. enumerable: true,
  102039. configurable: true
  102040. });
  102041. /**
  102042. * The entire material has been created in order to prevent overdraw.
  102043. * @returns false
  102044. */
  102045. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102046. return true;
  102047. };
  102048. /**
  102049. * The entire material has been created in order to prevent overdraw.
  102050. * @returns true if blending is enable
  102051. */
  102052. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102053. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102054. };
  102055. /**
  102056. * Checks wether the material is ready to be rendered for a given mesh.
  102057. * @param mesh The mesh to render
  102058. * @param subMesh The submesh to check against
  102059. * @param useInstances Specify wether or not the material is used with instances
  102060. * @returns true if all the dependencies are ready (Textures, Effects...)
  102061. */
  102062. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102063. var _this = this;
  102064. if (useInstances === void 0) { useInstances = false; }
  102065. if (subMesh.effect && this.isFrozen) {
  102066. if (this._wasPreviouslyReady) {
  102067. return true;
  102068. }
  102069. }
  102070. if (!subMesh._materialDefines) {
  102071. subMesh._materialDefines = new BackgroundMaterialDefines();
  102072. }
  102073. var scene = this.getScene();
  102074. var defines = subMesh._materialDefines;
  102075. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102076. if (defines._renderId === scene.getRenderId()) {
  102077. return true;
  102078. }
  102079. }
  102080. var engine = scene.getEngine();
  102081. // Lights
  102082. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102083. defines._needNormals = true;
  102084. // Textures
  102085. if (defines._areTexturesDirty) {
  102086. defines._needUVs = false;
  102087. if (scene.texturesEnabled) {
  102088. if (scene.getEngine().getCaps().textureLOD) {
  102089. defines.TEXTURELODSUPPORT = true;
  102090. }
  102091. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102092. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102093. return false;
  102094. }
  102095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102096. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102097. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102098. defines.OPACITYFRESNEL = this._opacityFresnel;
  102099. }
  102100. else {
  102101. defines.DIFFUSE = false;
  102102. defines.DIFFUSEHASALPHA = false;
  102103. defines.GAMMADIFFUSE = false;
  102104. defines.OPACITYFRESNEL = false;
  102105. }
  102106. var reflectionTexture = this._reflectionTexture;
  102107. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102108. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102109. return false;
  102110. }
  102111. defines.REFLECTION = true;
  102112. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102113. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102114. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102115. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102116. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102117. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102118. defines.REFLECTIONBGR = this.switchToBGR;
  102119. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102120. defines.INVERTCUBICMAP = true;
  102121. }
  102122. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102123. switch (reflectionTexture.coordinatesMode) {
  102124. case BABYLON.Texture.EXPLICIT_MODE:
  102125. defines.REFLECTIONMAP_EXPLICIT = true;
  102126. break;
  102127. case BABYLON.Texture.PLANAR_MODE:
  102128. defines.REFLECTIONMAP_PLANAR = true;
  102129. break;
  102130. case BABYLON.Texture.PROJECTION_MODE:
  102131. defines.REFLECTIONMAP_PROJECTION = true;
  102132. break;
  102133. case BABYLON.Texture.SKYBOX_MODE:
  102134. defines.REFLECTIONMAP_SKYBOX = true;
  102135. break;
  102136. case BABYLON.Texture.SPHERICAL_MODE:
  102137. defines.REFLECTIONMAP_SPHERICAL = true;
  102138. break;
  102139. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102140. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102141. break;
  102142. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102143. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102144. break;
  102145. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102146. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102147. break;
  102148. case BABYLON.Texture.CUBIC_MODE:
  102149. case BABYLON.Texture.INVCUBIC_MODE:
  102150. default:
  102151. defines.REFLECTIONMAP_CUBIC = true;
  102152. break;
  102153. }
  102154. if (this.reflectionFresnel) {
  102155. defines.REFLECTIONFRESNEL = true;
  102156. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102157. this._reflectionControls.x = this.reflectionAmount;
  102158. this._reflectionControls.y = this.reflectionReflectance0;
  102159. this._reflectionControls.z = this.reflectionReflectance90;
  102160. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102161. }
  102162. else {
  102163. defines.REFLECTIONFRESNEL = false;
  102164. defines.REFLECTIONFALLOFF = false;
  102165. }
  102166. }
  102167. else {
  102168. defines.REFLECTION = false;
  102169. defines.REFLECTIONFRESNEL = false;
  102170. defines.REFLECTIONFALLOFF = false;
  102171. defines.REFLECTIONBLUR = false;
  102172. defines.REFLECTIONMAP_3D = false;
  102173. defines.REFLECTIONMAP_SPHERICAL = false;
  102174. defines.REFLECTIONMAP_PLANAR = false;
  102175. defines.REFLECTIONMAP_CUBIC = false;
  102176. defines.REFLECTIONMAP_PROJECTION = false;
  102177. defines.REFLECTIONMAP_SKYBOX = false;
  102178. defines.REFLECTIONMAP_EXPLICIT = false;
  102179. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102180. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102181. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102182. defines.INVERTCUBICMAP = false;
  102183. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102184. defines.LODINREFLECTIONALPHA = false;
  102185. defines.GAMMAREFLECTION = false;
  102186. defines.RGBDREFLECTION = false;
  102187. }
  102188. }
  102189. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102190. defines.USERGBCOLOR = this._useRGBColor;
  102191. defines.NOISE = this._enableNoise;
  102192. }
  102193. if (defines._areLightsDirty) {
  102194. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102195. }
  102196. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102197. if (!this._imageProcessingConfiguration.isReady()) {
  102198. return false;
  102199. }
  102200. this._imageProcessingConfiguration.prepareDefines(defines);
  102201. }
  102202. // Misc.
  102203. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102204. // Values that need to be evaluated on every frame
  102205. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102206. // Attribs
  102207. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102208. if (mesh) {
  102209. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102210. mesh.createNormals(true);
  102211. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102212. }
  102213. }
  102214. }
  102215. // Get correct effect
  102216. if (defines.isDirty) {
  102217. defines.markAsProcessed();
  102218. scene.resetCachedMaterial();
  102219. // Fallbacks
  102220. var fallbacks = new BABYLON.EffectFallbacks();
  102221. if (defines.FOG) {
  102222. fallbacks.addFallback(0, "FOG");
  102223. }
  102224. if (defines.POINTSIZE) {
  102225. fallbacks.addFallback(1, "POINTSIZE");
  102226. }
  102227. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102228. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102229. fallbacks.addCPUSkinningFallback(0, mesh);
  102230. }
  102231. //Attributes
  102232. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102233. if (defines.NORMAL) {
  102234. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102235. }
  102236. if (defines.UV1) {
  102237. attribs.push(BABYLON.VertexBuffer.UVKind);
  102238. }
  102239. if (defines.UV2) {
  102240. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102241. }
  102242. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102243. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102244. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102245. "vFogInfos", "vFogColor", "pointSize",
  102246. "vClipPlane", "mBones",
  102247. "vPrimaryColor", "vPrimaryColorShadow",
  102248. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102249. "shadowLevel", "alpha",
  102250. "vBackgroundCenter", "vReflectionControl",
  102251. "vDiffuseInfos", "diffuseMatrix",
  102252. ];
  102253. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102254. var uniformBuffers = ["Material", "Scene"];
  102255. if (BABYLON.ImageProcessingConfiguration) {
  102256. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102257. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102258. }
  102259. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102260. uniformsNames: uniforms,
  102261. uniformBuffersNames: uniformBuffers,
  102262. samplers: samplers,
  102263. defines: defines,
  102264. maxSimultaneousLights: this._maxSimultaneousLights
  102265. });
  102266. var onCompiled = function (effect) {
  102267. if (_this.onCompiled) {
  102268. _this.onCompiled(effect);
  102269. }
  102270. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102271. };
  102272. var join = defines.toString();
  102273. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102274. attributes: attribs,
  102275. uniformsNames: uniforms,
  102276. uniformBuffersNames: uniformBuffers,
  102277. samplers: samplers,
  102278. defines: join,
  102279. fallbacks: fallbacks,
  102280. onCompiled: onCompiled,
  102281. onError: this.onError,
  102282. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102283. }, engine), defines);
  102284. this.buildUniformLayout();
  102285. }
  102286. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102287. return false;
  102288. }
  102289. defines._renderId = scene.getRenderId();
  102290. this._wasPreviouslyReady = true;
  102291. return true;
  102292. };
  102293. /**
  102294. * Compute the primary color according to the chosen perceptual color.
  102295. */
  102296. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102297. if (!this.__perceptualColor) {
  102298. return;
  102299. }
  102300. this._primaryColor.copyFrom(this.__perceptualColor);
  102301. // Revert gamma space.
  102302. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102303. // Revert image processing configuration.
  102304. if (this._imageProcessingConfiguration) {
  102305. // Revert Exposure.
  102306. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102307. }
  102308. this._computePrimaryColors();
  102309. };
  102310. /**
  102311. * Compute the highlights and shadow colors according to their chosen levels.
  102312. */
  102313. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102314. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102315. return;
  102316. }
  102317. // Find the highlight color based on the configuration.
  102318. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102319. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102320. // Find the shadow color based on the configuration.
  102321. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102322. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102323. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102324. };
  102325. /**
  102326. * Build the uniform buffer used in the material.
  102327. */
  102328. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102329. // Order is important !
  102330. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102331. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102332. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102333. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102334. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102335. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102336. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102337. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102338. this._uniformBuffer.addUniform("pointSize", 1);
  102339. this._uniformBuffer.addUniform("shadowLevel", 1);
  102340. this._uniformBuffer.addUniform("alpha", 1);
  102341. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102342. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102343. this._uniformBuffer.create();
  102344. };
  102345. /**
  102346. * Unbind the material.
  102347. */
  102348. BackgroundMaterial.prototype.unbind = function () {
  102349. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102350. this._uniformBuffer.setTexture("diffuseSampler", null);
  102351. }
  102352. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102353. this._uniformBuffer.setTexture("reflectionSampler", null);
  102354. }
  102355. _super.prototype.unbind.call(this);
  102356. };
  102357. /**
  102358. * Bind only the world matrix to the material.
  102359. * @param world The world matrix to bind.
  102360. */
  102361. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102362. this._activeEffect.setMatrix("world", world);
  102363. };
  102364. /**
  102365. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102366. * @param world The world matrix to bind.
  102367. * @param subMesh The submesh to bind for.
  102368. */
  102369. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102370. var scene = this.getScene();
  102371. var defines = subMesh._materialDefines;
  102372. if (!defines) {
  102373. return;
  102374. }
  102375. var effect = subMesh.effect;
  102376. if (!effect) {
  102377. return;
  102378. }
  102379. this._activeEffect = effect;
  102380. // Matrices
  102381. this.bindOnlyWorldMatrix(world);
  102382. // Bones
  102383. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102384. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102385. if (mustRebind) {
  102386. this._uniformBuffer.bindToEffect(effect, "Material");
  102387. this.bindViewProjection(effect);
  102388. var reflectionTexture = this._reflectionTexture;
  102389. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102390. // Texture uniforms
  102391. if (scene.texturesEnabled) {
  102392. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102393. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102394. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102395. }
  102396. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102397. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102398. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102399. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102400. }
  102401. }
  102402. if (this.shadowLevel > 0) {
  102403. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102404. }
  102405. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102406. // Point size
  102407. if (this.pointsCloud) {
  102408. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102409. }
  102410. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102411. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102412. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102413. }
  102414. else {
  102415. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102416. }
  102417. }
  102418. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102419. // Textures
  102420. if (scene.texturesEnabled) {
  102421. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102422. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102423. }
  102424. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102425. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102426. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102427. }
  102428. else if (!defines.REFLECTIONBLUR) {
  102429. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102430. }
  102431. else {
  102432. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102433. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102434. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102435. }
  102436. if (defines.REFLECTIONFRESNEL) {
  102437. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102438. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102439. }
  102440. }
  102441. }
  102442. // Clip plane
  102443. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102444. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102445. }
  102446. if (mustRebind || !this.isFrozen) {
  102447. if (scene.lightsEnabled) {
  102448. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102449. }
  102450. // View
  102451. this.bindView(effect);
  102452. // Fog
  102453. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102454. // image processing
  102455. if (this._imageProcessingConfiguration) {
  102456. this._imageProcessingConfiguration.bind(this._activeEffect);
  102457. }
  102458. }
  102459. this._uniformBuffer.update();
  102460. this._afterBind(mesh, this._activeEffect);
  102461. };
  102462. /**
  102463. * Dispose the material.
  102464. * @param forceDisposeEffect Force disposal of the associated effect.
  102465. * @param forceDisposeTextures Force disposal of the associated textures.
  102466. */
  102467. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102468. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102469. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102470. if (forceDisposeTextures) {
  102471. if (this.diffuseTexture) {
  102472. this.diffuseTexture.dispose();
  102473. }
  102474. if (this.reflectionTexture) {
  102475. this.reflectionTexture.dispose();
  102476. }
  102477. }
  102478. this._renderTargets.dispose();
  102479. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102480. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102481. }
  102482. _super.prototype.dispose.call(this, forceDisposeEffect);
  102483. };
  102484. /**
  102485. * Clones the material.
  102486. * @param name The cloned name.
  102487. * @returns The cloned material.
  102488. */
  102489. BackgroundMaterial.prototype.clone = function (name) {
  102490. var _this = this;
  102491. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102492. };
  102493. /**
  102494. * Serializes the current material to its JSON representation.
  102495. * @returns The JSON representation.
  102496. */
  102497. BackgroundMaterial.prototype.serialize = function () {
  102498. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102499. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102500. return serializationObject;
  102501. };
  102502. /**
  102503. * Gets the class name of the material
  102504. * @returns "BackgroundMaterial"
  102505. */
  102506. BackgroundMaterial.prototype.getClassName = function () {
  102507. return "BackgroundMaterial";
  102508. };
  102509. /**
  102510. * Parse a JSON input to create back a background material.
  102511. * @param source The JSON data to parse
  102512. * @param scene The scene to create the parsed material in
  102513. * @param rootUrl The root url of the assets the material depends upon
  102514. * @returns the instantiated BackgroundMaterial.
  102515. */
  102516. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102517. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102518. };
  102519. /**
  102520. * Standard reflectance value at parallel view angle.
  102521. */
  102522. BackgroundMaterial.StandardReflectance0 = 0.05;
  102523. /**
  102524. * Standard reflectance value at grazing angle.
  102525. */
  102526. BackgroundMaterial.StandardReflectance90 = 0.5;
  102527. __decorate([
  102528. BABYLON.serializeAsColor3()
  102529. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102530. __decorate([
  102531. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102532. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102533. __decorate([
  102534. BABYLON.serializeAsColor3()
  102535. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102536. __decorate([
  102537. BABYLON.serialize()
  102538. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102539. __decorate([
  102540. BABYLON.serialize()
  102541. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102542. __decorate([
  102543. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102544. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102545. __decorate([
  102546. BABYLON.serializeAsTexture()
  102547. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102548. __decorate([
  102549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102550. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102551. __decorate([
  102552. BABYLON.serialize()
  102553. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102554. __decorate([
  102555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102556. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102557. __decorate([
  102558. BABYLON.serializeAsTexture()
  102559. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102560. __decorate([
  102561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102562. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102563. __decorate([
  102564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102565. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102566. __decorate([
  102567. BABYLON.serialize()
  102568. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102569. __decorate([
  102570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102571. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102572. __decorate([
  102573. BABYLON.serializeAsVector3()
  102574. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102575. __decorate([
  102576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102577. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102578. __decorate([
  102579. BABYLON.serialize()
  102580. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102581. __decorate([
  102582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102583. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102584. __decorate([
  102585. BABYLON.serialize()
  102586. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102587. __decorate([
  102588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102589. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102590. __decorate([
  102591. BABYLON.serialize()
  102592. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102593. __decorate([
  102594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102595. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102596. __decorate([
  102597. BABYLON.serialize()
  102598. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102599. __decorate([
  102600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102601. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102602. __decorate([
  102603. BABYLON.serialize()
  102604. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102605. __decorate([
  102606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102607. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102608. __decorate([
  102609. BABYLON.serialize()
  102610. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102611. __decorate([
  102612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102613. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102614. __decorate([
  102615. BABYLON.serialize()
  102616. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102617. __decorate([
  102618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102619. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102620. __decorate([
  102621. BABYLON.serialize()
  102622. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102623. __decorate([
  102624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102625. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102626. __decorate([
  102627. BABYLON.serialize()
  102628. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102629. __decorate([
  102630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102631. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102632. __decorate([
  102633. BABYLON.serializeAsImageProcessingConfiguration()
  102634. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102635. return BackgroundMaterial;
  102636. }(BABYLON.PushMaterial));
  102637. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102638. })(BABYLON || (BABYLON = {}));
  102639. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102640. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102641. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102642. s = arguments[i];
  102643. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102644. t[p] = s[p];
  102645. }
  102646. return t;
  102647. };
  102648. var BABYLON;
  102649. (function (BABYLON) {
  102650. /**
  102651. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102652. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102653. * It also helps with the default setup of your imageProcessing configuration.
  102654. */
  102655. var EnvironmentHelper = /** @class */ (function () {
  102656. /**
  102657. * constructor
  102658. * @param options
  102659. * @param scene The scene to add the material to
  102660. */
  102661. function EnvironmentHelper(options, scene) {
  102662. var _this = this;
  102663. this._errorHandler = function (message, exception) {
  102664. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102665. };
  102666. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102667. this._scene = scene;
  102668. this.onErrorObservable = new BABYLON.Observable();
  102669. this._setupBackground();
  102670. this._setupImageProcessing();
  102671. }
  102672. /**
  102673. * Creates the default options for the helper.
  102674. */
  102675. EnvironmentHelper._getDefaultOptions = function () {
  102676. return {
  102677. createGround: true,
  102678. groundSize: 15,
  102679. groundTexture: this._groundTextureCDNUrl,
  102680. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102681. groundOpacity: 0.9,
  102682. enableGroundShadow: true,
  102683. groundShadowLevel: 0.5,
  102684. enableGroundMirror: false,
  102685. groundMirrorSizeRatio: 0.3,
  102686. groundMirrorBlurKernel: 64,
  102687. groundMirrorAmount: 1,
  102688. groundMirrorFresnelWeight: 1,
  102689. groundMirrorFallOffDistance: 0,
  102690. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102691. groundYBias: 0.00001,
  102692. createSkybox: true,
  102693. skyboxSize: 20,
  102694. skyboxTexture: this._skyboxTextureCDNUrl,
  102695. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102696. backgroundYRotation: 0,
  102697. sizeAuto: true,
  102698. rootPosition: BABYLON.Vector3.Zero(),
  102699. setupImageProcessing: true,
  102700. environmentTexture: this._environmentTextureCDNUrl,
  102701. cameraExposure: 0.8,
  102702. cameraContrast: 1.2,
  102703. toneMappingEnabled: true,
  102704. };
  102705. };
  102706. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102707. /**
  102708. * Gets the root mesh created by the helper.
  102709. */
  102710. get: function () {
  102711. return this._rootMesh;
  102712. },
  102713. enumerable: true,
  102714. configurable: true
  102715. });
  102716. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102717. /**
  102718. * Gets the skybox created by the helper.
  102719. */
  102720. get: function () {
  102721. return this._skybox;
  102722. },
  102723. enumerable: true,
  102724. configurable: true
  102725. });
  102726. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102727. /**
  102728. * Gets the skybox texture created by the helper.
  102729. */
  102730. get: function () {
  102731. return this._skyboxTexture;
  102732. },
  102733. enumerable: true,
  102734. configurable: true
  102735. });
  102736. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102737. /**
  102738. * Gets the skybox material created by the helper.
  102739. */
  102740. get: function () {
  102741. return this._skyboxMaterial;
  102742. },
  102743. enumerable: true,
  102744. configurable: true
  102745. });
  102746. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102747. /**
  102748. * Gets the ground mesh created by the helper.
  102749. */
  102750. get: function () {
  102751. return this._ground;
  102752. },
  102753. enumerable: true,
  102754. configurable: true
  102755. });
  102756. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102757. /**
  102758. * Gets the ground texture created by the helper.
  102759. */
  102760. get: function () {
  102761. return this._groundTexture;
  102762. },
  102763. enumerable: true,
  102764. configurable: true
  102765. });
  102766. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102767. /**
  102768. * Gets the ground mirror created by the helper.
  102769. */
  102770. get: function () {
  102771. return this._groundMirror;
  102772. },
  102773. enumerable: true,
  102774. configurable: true
  102775. });
  102776. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102777. /**
  102778. * Gets the ground mirror render list to helps pushing the meshes
  102779. * you wish in the ground reflection.
  102780. */
  102781. get: function () {
  102782. if (this._groundMirror) {
  102783. return this._groundMirror.renderList;
  102784. }
  102785. return null;
  102786. },
  102787. enumerable: true,
  102788. configurable: true
  102789. });
  102790. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102791. /**
  102792. * Gets the ground material created by the helper.
  102793. */
  102794. get: function () {
  102795. return this._groundMaterial;
  102796. },
  102797. enumerable: true,
  102798. configurable: true
  102799. });
  102800. /**
  102801. * Updates the background according to the new options
  102802. * @param options
  102803. */
  102804. EnvironmentHelper.prototype.updateOptions = function (options) {
  102805. var newOptions = __assign({}, this._options, options);
  102806. if (this._ground && !newOptions.createGround) {
  102807. this._ground.dispose();
  102808. this._ground = null;
  102809. }
  102810. if (this._groundMaterial && !newOptions.createGround) {
  102811. this._groundMaterial.dispose();
  102812. this._groundMaterial = null;
  102813. }
  102814. if (this._groundTexture) {
  102815. if (this._options.groundTexture != newOptions.groundTexture) {
  102816. this._groundTexture.dispose();
  102817. this._groundTexture = null;
  102818. }
  102819. }
  102820. if (this._skybox && !newOptions.createSkybox) {
  102821. this._skybox.dispose();
  102822. this._skybox = null;
  102823. }
  102824. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102825. this._skyboxMaterial.dispose();
  102826. this._skyboxMaterial = null;
  102827. }
  102828. if (this._skyboxTexture) {
  102829. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102830. this._skyboxTexture.dispose();
  102831. this._skyboxTexture = null;
  102832. }
  102833. }
  102834. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102835. this._groundMirror.dispose();
  102836. this._groundMirror = null;
  102837. }
  102838. if (this._scene.environmentTexture) {
  102839. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102840. this._scene.environmentTexture.dispose();
  102841. }
  102842. }
  102843. this._options = newOptions;
  102844. this._setupBackground();
  102845. this._setupImageProcessing();
  102846. };
  102847. /**
  102848. * Sets the primary color of all the available elements.
  102849. * @param color the main color to affect to the ground and the background
  102850. */
  102851. EnvironmentHelper.prototype.setMainColor = function (color) {
  102852. if (this.groundMaterial) {
  102853. this.groundMaterial.primaryColor = color;
  102854. }
  102855. if (this.skyboxMaterial) {
  102856. this.skyboxMaterial.primaryColor = color;
  102857. }
  102858. if (this.groundMirror) {
  102859. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102860. }
  102861. };
  102862. /**
  102863. * Setup the image processing according to the specified options.
  102864. */
  102865. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102866. if (this._options.setupImageProcessing) {
  102867. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102868. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102869. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102870. this._setupEnvironmentTexture();
  102871. }
  102872. };
  102873. /**
  102874. * Setup the environment texture according to the specified options.
  102875. */
  102876. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102877. if (this._scene.environmentTexture) {
  102878. return;
  102879. }
  102880. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102881. this._scene.environmentTexture = this._options.environmentTexture;
  102882. return;
  102883. }
  102884. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102885. this._scene.environmentTexture = environmentTexture;
  102886. };
  102887. /**
  102888. * Setup the background according to the specified options.
  102889. */
  102890. EnvironmentHelper.prototype._setupBackground = function () {
  102891. if (!this._rootMesh) {
  102892. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102893. }
  102894. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102895. var sceneSize = this._getSceneSize();
  102896. if (this._options.createGround) {
  102897. this._setupGround(sceneSize);
  102898. this._setupGroundMaterial();
  102899. this._setupGroundDiffuseTexture();
  102900. if (this._options.enableGroundMirror) {
  102901. this._setupGroundMirrorTexture(sceneSize);
  102902. }
  102903. this._setupMirrorInGroundMaterial();
  102904. }
  102905. if (this._options.createSkybox) {
  102906. this._setupSkybox(sceneSize);
  102907. this._setupSkyboxMaterial();
  102908. this._setupSkyboxReflectionTexture();
  102909. }
  102910. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102911. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102912. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102913. };
  102914. /**
  102915. * Get the scene sizes according to the setup.
  102916. */
  102917. EnvironmentHelper.prototype._getSceneSize = function () {
  102918. var _this = this;
  102919. var groundSize = this._options.groundSize;
  102920. var skyboxSize = this._options.skyboxSize;
  102921. var rootPosition = this._options.rootPosition;
  102922. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102923. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102924. }
  102925. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102926. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102927. });
  102928. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102929. if (this._options.sizeAuto) {
  102930. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102931. this._scene.activeCamera.upperRadiusLimit) {
  102932. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102933. skyboxSize = groundSize;
  102934. }
  102935. var sceneDiagonalLenght = sceneDiagonal.length();
  102936. if (sceneDiagonalLenght > groundSize) {
  102937. groundSize = sceneDiagonalLenght * 2;
  102938. skyboxSize = groundSize;
  102939. }
  102940. // 10 % bigger.
  102941. groundSize *= 1.1;
  102942. skyboxSize *= 1.5;
  102943. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102944. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102945. }
  102946. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102947. };
  102948. /**
  102949. * Setup the ground according to the specified options.
  102950. */
  102951. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102952. var _this = this;
  102953. if (!this._ground || this._ground.isDisposed()) {
  102954. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102955. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102956. this._ground.parent = this._rootMesh;
  102957. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102958. }
  102959. this._ground.receiveShadows = this._options.enableGroundShadow;
  102960. };
  102961. /**
  102962. * Setup the ground material according to the specified options.
  102963. */
  102964. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102965. if (!this._groundMaterial) {
  102966. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102967. }
  102968. this._groundMaterial.alpha = this._options.groundOpacity;
  102969. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102970. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102971. this._groundMaterial.primaryColor = this._options.groundColor;
  102972. this._groundMaterial.useRGBColor = false;
  102973. this._groundMaterial.enableNoise = true;
  102974. if (this._ground) {
  102975. this._ground.material = this._groundMaterial;
  102976. }
  102977. };
  102978. /**
  102979. * Setup the ground diffuse texture according to the specified options.
  102980. */
  102981. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102982. if (!this._groundMaterial) {
  102983. return;
  102984. }
  102985. if (this._groundTexture) {
  102986. return;
  102987. }
  102988. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102989. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102990. return;
  102991. }
  102992. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102993. diffuseTexture.gammaSpace = false;
  102994. diffuseTexture.hasAlpha = true;
  102995. this._groundMaterial.diffuseTexture = diffuseTexture;
  102996. };
  102997. /**
  102998. * Setup the ground mirror texture according to the specified options.
  102999. */
  103000. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103001. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103002. if (!this._groundMirror) {
  103003. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103004. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103005. this._groundMirror.anisotropicFilteringLevel = 1;
  103006. this._groundMirror.wrapU = wrapping;
  103007. this._groundMirror.wrapV = wrapping;
  103008. this._groundMirror.gammaSpace = false;
  103009. if (this._groundMirror.renderList) {
  103010. for (var i = 0; i < this._scene.meshes.length; i++) {
  103011. var mesh = this._scene.meshes[i];
  103012. if (mesh !== this._ground &&
  103013. mesh !== this._skybox &&
  103014. mesh !== this._rootMesh) {
  103015. this._groundMirror.renderList.push(mesh);
  103016. }
  103017. }
  103018. }
  103019. }
  103020. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103021. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103022. };
  103023. /**
  103024. * Setup the ground to receive the mirror texture.
  103025. */
  103026. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103027. if (this._groundMaterial) {
  103028. this._groundMaterial.reflectionTexture = this._groundMirror;
  103029. this._groundMaterial.reflectionFresnel = true;
  103030. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103031. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103032. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103033. }
  103034. };
  103035. /**
  103036. * Setup the skybox according to the specified options.
  103037. */
  103038. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103039. var _this = this;
  103040. if (!this._skybox || this._skybox.isDisposed()) {
  103041. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103042. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103043. }
  103044. this._skybox.parent = this._rootMesh;
  103045. };
  103046. /**
  103047. * Setup the skybox material according to the specified options.
  103048. */
  103049. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103050. if (!this._skybox) {
  103051. return;
  103052. }
  103053. if (!this._skyboxMaterial) {
  103054. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103055. }
  103056. this._skyboxMaterial.useRGBColor = false;
  103057. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103058. this._skyboxMaterial.enableNoise = true;
  103059. this._skybox.material = this._skyboxMaterial;
  103060. };
  103061. /**
  103062. * Setup the skybox reflection texture according to the specified options.
  103063. */
  103064. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103065. if (!this._skyboxMaterial) {
  103066. return;
  103067. }
  103068. if (this._skyboxTexture) {
  103069. return;
  103070. }
  103071. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103072. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103073. return;
  103074. }
  103075. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103076. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103077. this._skyboxTexture.gammaSpace = false;
  103078. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103079. };
  103080. /**
  103081. * Dispose all the elements created by the Helper.
  103082. */
  103083. EnvironmentHelper.prototype.dispose = function () {
  103084. if (this._groundMaterial) {
  103085. this._groundMaterial.dispose(true, true);
  103086. }
  103087. if (this._skyboxMaterial) {
  103088. this._skyboxMaterial.dispose(true, true);
  103089. }
  103090. this._rootMesh.dispose(false);
  103091. };
  103092. /**
  103093. * Default ground texture URL.
  103094. */
  103095. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103096. /**
  103097. * Default skybox texture URL.
  103098. */
  103099. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103100. /**
  103101. * Default environment texture URL.
  103102. */
  103103. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103104. return EnvironmentHelper;
  103105. }());
  103106. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103107. })(BABYLON || (BABYLON = {}));
  103108. //# sourceMappingURL=babylon.environmentHelper.js.map
  103109. var BABYLON;
  103110. (function (BABYLON) {
  103111. /** Internal class used to store shapes for emitters */
  103112. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103113. function ParticleSystemSetEmitterCreationOptions() {
  103114. }
  103115. return ParticleSystemSetEmitterCreationOptions;
  103116. }());
  103117. /**
  103118. * Represents a set of particle systems working together to create a specific effect
  103119. */
  103120. var ParticleSystemSet = /** @class */ (function () {
  103121. function ParticleSystemSet() {
  103122. /**
  103123. * Gets the particle system list
  103124. */
  103125. this.systems = new Array();
  103126. }
  103127. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103128. /**
  103129. * Gets the emitter node used with this set
  103130. */
  103131. get: function () {
  103132. return this._emitterNode;
  103133. },
  103134. enumerable: true,
  103135. configurable: true
  103136. });
  103137. /**
  103138. * Creates a new emitter mesh as a sphere
  103139. * @param options defines the options used to create the sphere
  103140. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103141. * @param scene defines the hosting scene
  103142. */
  103143. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103144. if (this._emitterNode) {
  103145. this._emitterNode.dispose();
  103146. }
  103147. this._emitterCreationOptions = {
  103148. kind: "Sphere",
  103149. options: options,
  103150. renderingGroupId: renderingGroupId
  103151. };
  103152. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103153. emitterMesh.renderingGroupId = renderingGroupId;
  103154. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103155. material.emissiveColor = options.color;
  103156. emitterMesh.material = material;
  103157. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103158. var system = _a[_i];
  103159. system.emitter = emitterMesh;
  103160. }
  103161. this._emitterNode = emitterMesh;
  103162. };
  103163. /**
  103164. * Starts all particle systems of the set
  103165. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103166. */
  103167. ParticleSystemSet.prototype.start = function (emitter) {
  103168. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103169. var system = _a[_i];
  103170. if (emitter) {
  103171. system.emitter = emitter;
  103172. }
  103173. system.start();
  103174. }
  103175. };
  103176. /**
  103177. * Release all associated resources
  103178. */
  103179. ParticleSystemSet.prototype.dispose = function () {
  103180. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103181. var system = _a[_i];
  103182. system.dispose();
  103183. }
  103184. this.systems = [];
  103185. if (this._emitterNode) {
  103186. this._emitterNode.dispose();
  103187. this._emitterNode = null;
  103188. }
  103189. };
  103190. /**
  103191. * Serialize the set into a JSON compatible object
  103192. * @returns a JSON compatible representation of the set
  103193. */
  103194. ParticleSystemSet.prototype.serialize = function () {
  103195. var result = {};
  103196. result.systems = [];
  103197. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103198. var system = _a[_i];
  103199. result.systems.push(system.serialize());
  103200. }
  103201. if (this._emitterNode) {
  103202. result.emitter = this._emitterCreationOptions;
  103203. }
  103204. return result;
  103205. };
  103206. /**
  103207. * Parse a new ParticleSystemSet from a serialized source
  103208. * @param data defines a JSON compatible representation of the set
  103209. * @param scene defines the hosting scene
  103210. * @param gpu defines if we want GPU particles or CPU particles
  103211. * @returns a new ParticleSystemSet
  103212. */
  103213. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103214. if (gpu === void 0) { gpu = false; }
  103215. var result = new ParticleSystemSet();
  103216. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103217. scene = scene || BABYLON.Engine.LastCreatedScene;
  103218. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103219. var system = _a[_i];
  103220. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103221. }
  103222. if (data.emitter) {
  103223. var options = data.emitter.options;
  103224. switch (data.emitter.kind) {
  103225. case "Sphere":
  103226. result.setEmitterAsSphere({
  103227. diameter: options.diameter,
  103228. segments: options.segments,
  103229. color: BABYLON.Color3.FromArray(options.color)
  103230. }, data.emitter.renderingGroupId, scene);
  103231. break;
  103232. }
  103233. }
  103234. return result;
  103235. };
  103236. return ParticleSystemSet;
  103237. }());
  103238. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103239. })(BABYLON || (BABYLON = {}));
  103240. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103241. var BABYLON;
  103242. (function (BABYLON) {
  103243. /**
  103244. * This class is made for on one-liner static method to help creating particle system set.
  103245. */
  103246. var ParticleHelper = /** @class */ (function () {
  103247. function ParticleHelper() {
  103248. }
  103249. /**
  103250. * This is the main static method (one-liner) of this helper to create different particle systems
  103251. * @param type This string represents the type to the particle system to create
  103252. * @param scene The scene where the particle system should live
  103253. * @param gpu If the system will use gpu
  103254. * @returns the ParticleSystemSet created
  103255. */
  103256. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103257. if (gpu === void 0) { gpu = false; }
  103258. if (!scene) {
  103259. scene = BABYLON.Engine.LastCreatedScene;
  103260. ;
  103261. }
  103262. var token = {};
  103263. scene._addPendingData(token);
  103264. return new Promise(function (resolve, reject) {
  103265. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103266. scene._removePendingData(token);
  103267. return reject("Particle system with GPU is not supported.");
  103268. }
  103269. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103270. scene._removePendingData(token);
  103271. var newData = JSON.parse(data.toString());
  103272. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103273. }, undefined, undefined, undefined, function (req, exception) {
  103274. scene._removePendingData(token);
  103275. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103276. });
  103277. });
  103278. };
  103279. /**
  103280. * Static function used to export a particle system to a ParticleSystemSet variable.
  103281. * Please note that the emitter shape is not exported
  103282. * @param system defines the particle systems to export
  103283. */
  103284. ParticleHelper.ExportSet = function (systems) {
  103285. var set = new BABYLON.ParticleSystemSet();
  103286. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103287. var system = systems_1[_i];
  103288. set.systems.push(system);
  103289. }
  103290. return set;
  103291. };
  103292. /**
  103293. * Gets or sets base Assets URL
  103294. */
  103295. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103296. return ParticleHelper;
  103297. }());
  103298. BABYLON.ParticleHelper = ParticleHelper;
  103299. })(BABYLON || (BABYLON = {}));
  103300. //# sourceMappingURL=babylon.particleHelper.js.map
  103301. var BABYLON;
  103302. (function (BABYLON) {
  103303. /**
  103304. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103305. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103306. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103307. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103308. */
  103309. var VideoDome = /** @class */ (function (_super) {
  103310. __extends(VideoDome, _super);
  103311. /**
  103312. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103313. * @param name Element's name, child elements will append suffixes for their own names.
  103314. * @param urlsOrVideo defines the url(s) or the video element to use
  103315. * @param options An object containing optional or exposed sub element properties
  103316. */
  103317. function VideoDome(name, urlsOrVideo, options, scene) {
  103318. var _this = _super.call(this, name, scene) || this;
  103319. _this._useDirectMapping = false;
  103320. // set defaults and manage values
  103321. name = name || "videoDome";
  103322. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103323. options.clickToPlay = Boolean(options.clickToPlay);
  103324. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103325. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103326. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103327. if (options.useDirectMapping === undefined) {
  103328. _this._useDirectMapping = true;
  103329. }
  103330. else {
  103331. _this._useDirectMapping = options.useDirectMapping;
  103332. }
  103333. // create
  103334. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103335. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103336. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103337. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103338. // configure material
  103339. material.useEquirectangularFOV = true;
  103340. material.fovMultiplier = 1.0;
  103341. material.opacityFresnel = false;
  103342. if (_this._useDirectMapping) {
  103343. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103344. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103345. material.diffuseTexture = texture;
  103346. }
  103347. else {
  103348. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103349. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103350. material.reflectionTexture = texture;
  103351. }
  103352. // configure mesh
  103353. _this._mesh.material = material;
  103354. _this._mesh.parent = _this;
  103355. // optional configuration
  103356. if (options.clickToPlay) {
  103357. scene.onPointerUp = function () {
  103358. _this._videoTexture.video.play();
  103359. };
  103360. }
  103361. return _this;
  103362. }
  103363. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103364. /**
  103365. * Gets the video texture being displayed on the sphere
  103366. */
  103367. get: function () {
  103368. return this._videoTexture;
  103369. },
  103370. enumerable: true,
  103371. configurable: true
  103372. });
  103373. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103374. /**
  103375. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103376. * Also see the options.resolution property.
  103377. */
  103378. get: function () {
  103379. return this._material.fovMultiplier;
  103380. },
  103381. set: function (value) {
  103382. this._material.fovMultiplier = value;
  103383. },
  103384. enumerable: true,
  103385. configurable: true
  103386. });
  103387. /**
  103388. * Releases resources associated with this node.
  103389. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103390. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103391. */
  103392. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103393. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103394. this._videoTexture.dispose();
  103395. this._mesh.dispose();
  103396. this._material.dispose();
  103397. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103398. };
  103399. return VideoDome;
  103400. }(BABYLON.Node));
  103401. BABYLON.VideoDome = VideoDome;
  103402. })(BABYLON || (BABYLON = {}));
  103403. //# sourceMappingURL=babylon.videoDome.js.map
  103404. var BABYLON;
  103405. (function (BABYLON) {
  103406. /**
  103407. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103408. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103409. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103410. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103411. */
  103412. var PhotoDome = /** @class */ (function (_super) {
  103413. __extends(PhotoDome, _super);
  103414. /**
  103415. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103416. * @param name Element's name, child elements will append suffixes for their own names.
  103417. * @param urlsOfPhoto define the url of the photo to display
  103418. * @param options An object containing optional or exposed sub element properties
  103419. */
  103420. function PhotoDome(name, urlOfPhoto, options, scene) {
  103421. var _this = _super.call(this, name, scene) || this;
  103422. _this._useDirectMapping = false;
  103423. // set defaults and manage values
  103424. name = name || "photoDome";
  103425. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103426. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103427. if (options.useDirectMapping === undefined) {
  103428. _this._useDirectMapping = true;
  103429. }
  103430. else {
  103431. _this._useDirectMapping = options.useDirectMapping;
  103432. }
  103433. // create
  103434. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103435. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103436. // configure material
  103437. material.opacityFresnel = false;
  103438. material.useEquirectangularFOV = true;
  103439. material.fovMultiplier = 1.0;
  103440. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103441. // configure mesh
  103442. _this._mesh.material = material;
  103443. _this._mesh.parent = _this;
  103444. return _this;
  103445. }
  103446. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103447. /**
  103448. * Gets or sets the texture being displayed on the sphere
  103449. */
  103450. get: function () {
  103451. return this._photoTexture;
  103452. },
  103453. set: function (value) {
  103454. if (this._photoTexture === value) {
  103455. return;
  103456. }
  103457. this._photoTexture = value;
  103458. if (this._useDirectMapping) {
  103459. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103460. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103461. this._material.diffuseTexture = this._photoTexture;
  103462. }
  103463. else {
  103464. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103465. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103466. this._material.reflectionTexture = this._photoTexture;
  103467. }
  103468. },
  103469. enumerable: true,
  103470. configurable: true
  103471. });
  103472. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103473. /**
  103474. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103475. * Also see the options.resolution property.
  103476. */
  103477. get: function () {
  103478. return this._material.fovMultiplier;
  103479. },
  103480. set: function (value) {
  103481. this._material.fovMultiplier = value;
  103482. },
  103483. enumerable: true,
  103484. configurable: true
  103485. });
  103486. /**
  103487. * Releases resources associated with this node.
  103488. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103489. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103490. */
  103491. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103492. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103493. this._photoTexture.dispose();
  103494. this._mesh.dispose();
  103495. this._material.dispose();
  103496. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103497. };
  103498. return PhotoDome;
  103499. }(BABYLON.Node));
  103500. BABYLON.PhotoDome = PhotoDome;
  103501. })(BABYLON || (BABYLON = {}));
  103502. //# sourceMappingURL=babylon.photoDome.js.map
  103503. var BABYLON;
  103504. (function (BABYLON) {
  103505. BABYLON.Engine.prototype.createQuery = function () {
  103506. return this._gl.createQuery();
  103507. };
  103508. BABYLON.Engine.prototype.deleteQuery = function (query) {
  103509. this._gl.deleteQuery(query);
  103510. return this;
  103511. };
  103512. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  103513. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  103514. };
  103515. BABYLON.Engine.prototype.getQueryResult = function (query) {
  103516. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  103517. };
  103518. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  103519. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103520. this._gl.beginQuery(glAlgorithm, query);
  103521. return this;
  103522. };
  103523. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  103524. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  103525. this._gl.endQuery(glAlgorithm);
  103526. return this;
  103527. };
  103528. BABYLON.Engine.prototype._createTimeQuery = function () {
  103529. var timerQuery = this.getCaps().timerQuery;
  103530. if (timerQuery.createQueryEXT) {
  103531. return timerQuery.createQueryEXT();
  103532. }
  103533. return this.createQuery();
  103534. };
  103535. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  103536. var timerQuery = this.getCaps().timerQuery;
  103537. if (timerQuery.deleteQueryEXT) {
  103538. timerQuery.deleteQueryEXT(query);
  103539. return;
  103540. }
  103541. this.deleteQuery(query);
  103542. };
  103543. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  103544. var timerQuery = this.getCaps().timerQuery;
  103545. if (timerQuery.getQueryObjectEXT) {
  103546. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  103547. }
  103548. return this.getQueryResult(query);
  103549. };
  103550. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  103551. var timerQuery = this.getCaps().timerQuery;
  103552. if (timerQuery.getQueryObjectEXT) {
  103553. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  103554. }
  103555. return this.isQueryResultAvailable(query);
  103556. };
  103557. BABYLON.Engine.prototype.startTimeQuery = function () {
  103558. var caps = this.getCaps();
  103559. var timerQuery = caps.timerQuery;
  103560. if (!timerQuery) {
  103561. return null;
  103562. }
  103563. var token = new BABYLON._TimeToken();
  103564. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103565. if (caps.canUseTimestampForTimerQuery) {
  103566. token._startTimeQuery = this._createTimeQuery();
  103567. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  103568. }
  103569. else {
  103570. if (this._currentNonTimestampToken) {
  103571. return this._currentNonTimestampToken;
  103572. }
  103573. token._timeElapsedQuery = this._createTimeQuery();
  103574. if (timerQuery.beginQueryEXT) {
  103575. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103576. }
  103577. else {
  103578. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  103579. }
  103580. this._currentNonTimestampToken = token;
  103581. }
  103582. return token;
  103583. };
  103584. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  103585. var caps = this.getCaps();
  103586. var timerQuery = caps.timerQuery;
  103587. if (!timerQuery || !token) {
  103588. return -1;
  103589. }
  103590. if (caps.canUseTimestampForTimerQuery) {
  103591. if (!token._startTimeQuery) {
  103592. return -1;
  103593. }
  103594. if (!token._endTimeQuery) {
  103595. token._endTimeQuery = this._createTimeQuery();
  103596. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  103597. }
  103598. }
  103599. else if (!token._timeElapsedQueryEnded) {
  103600. if (!token._timeElapsedQuery) {
  103601. return -1;
  103602. }
  103603. if (timerQuery.endQueryEXT) {
  103604. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  103605. }
  103606. else {
  103607. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  103608. }
  103609. token._timeElapsedQueryEnded = true;
  103610. }
  103611. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  103612. var available = false;
  103613. if (token._endTimeQuery) {
  103614. available = this._getTimeQueryAvailability(token._endTimeQuery);
  103615. }
  103616. else if (token._timeElapsedQuery) {
  103617. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  103618. }
  103619. if (available && !disjoint) {
  103620. var result = 0;
  103621. if (caps.canUseTimestampForTimerQuery) {
  103622. if (!token._startTimeQuery || !token._endTimeQuery) {
  103623. return -1;
  103624. }
  103625. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  103626. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  103627. result = timeEnd - timeStart;
  103628. this._deleteTimeQuery(token._startTimeQuery);
  103629. this._deleteTimeQuery(token._endTimeQuery);
  103630. token._startTimeQuery = null;
  103631. token._endTimeQuery = null;
  103632. }
  103633. else {
  103634. if (!token._timeElapsedQuery) {
  103635. return -1;
  103636. }
  103637. result = this._getTimeQueryResult(token._timeElapsedQuery);
  103638. this._deleteTimeQuery(token._timeElapsedQuery);
  103639. token._timeElapsedQuery = null;
  103640. token._timeElapsedQueryEnded = false;
  103641. this._currentNonTimestampToken = null;
  103642. }
  103643. return result;
  103644. }
  103645. return -1;
  103646. };
  103647. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  103648. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  103649. };
  103650. })(BABYLON || (BABYLON = {}));
  103651. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  103652. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute 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}","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 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 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 BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\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;\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","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  103653. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};