babylon.engine.ts 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399
  1. module BABYLON {
  2. /**
  3. * Keeps track of all the buffer info used in engine.
  4. */
  5. class BufferPointer {
  6. public active: boolean;
  7. public index: number;
  8. public size: number;
  9. public type: number;
  10. public normalized: boolean;
  11. public stride: number;
  12. public offset: number;
  13. public buffer: WebGLBuffer;
  14. }
  15. /**
  16. * Interface for attribute information associated with buffer instanciation
  17. */
  18. export class InstancingAttributeInfo {
  19. /**
  20. * Index/offset of the attribute in the vertex shader
  21. */
  22. index: number;
  23. /**
  24. * size of the attribute, 1, 2, 3 or 4
  25. */
  26. attributeSize: number;
  27. /**
  28. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  29. * default is FLOAT
  30. */
  31. attribyteType: number;
  32. /**
  33. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  34. */
  35. normalized: boolean;
  36. /**
  37. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  38. */
  39. offset: number;
  40. /**
  41. * Name of the GLSL attribute, for debugging purpose only
  42. */
  43. attributeName: string;
  44. }
  45. /**
  46. * Define options used to create a render target texture
  47. */
  48. export class RenderTargetCreationOptions {
  49. /**
  50. * Specifies is mipmaps must be generated
  51. */
  52. generateMipMaps?: boolean;
  53. /** Specifies whether or not a depth should be allocated in the texture (true by default) */
  54. generateDepthBuffer?: boolean;
  55. /** Specifies whether or not a stencil should be allocated in the texture (false by default)*/
  56. generateStencilBuffer?: boolean;
  57. /** Defines texture type (int by default) */
  58. type?: number;
  59. /** Defines sampling mode (trilinear by default) */
  60. samplingMode?: number;
  61. /** Defines format (RGBA by default) */
  62. format?: number;
  63. }
  64. /**
  65. * Define options used to create a depth texture
  66. */
  67. export class DepthTextureCreationOptions {
  68. /** Specifies whether or not a stencil should be allocated in the texture */
  69. generateStencil?: boolean;
  70. /** Specifies whether or not bilinear filtering is enable on the texture */
  71. bilinearFiltering?: boolean;
  72. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  73. comparisonFunction?: number;
  74. /** Specifies if the created texture is a cube texture */
  75. isCube?: boolean;
  76. }
  77. /**
  78. * Class used to describe the capabilities of the engine relatively to the current browser
  79. */
  80. export class EngineCapabilities {
  81. /** Maximum textures units per fragment shader */
  82. public maxTexturesImageUnits: number;
  83. /** Maximum texture units per vertex shader */
  84. public maxVertexTextureImageUnits: number;
  85. /** Maximum textures units in the entire pipeline */
  86. public maxCombinedTexturesImageUnits: number;
  87. /** Maximum texture size */
  88. public maxTextureSize: number;
  89. /** Maximum cube texture size */
  90. public maxCubemapTextureSize: number;
  91. /** Maximum render texture size */
  92. public maxRenderTextureSize: number;
  93. /** Maximum number of vertex attributes */
  94. public maxVertexAttribs: number;
  95. /** Maximum number of varyings */
  96. public maxVaryingVectors: number;
  97. /** Maximum number of uniforms per vertex shader */
  98. public maxVertexUniformVectors: number;
  99. /** Maximum number of uniforms per fragment shader */
  100. public maxFragmentUniformVectors: number;
  101. /** Defines if standard derivates (dx/dy) are supported */
  102. public standardDerivatives: boolean;
  103. /** Defines if s3tc texture compression is supported */
  104. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  105. /** Defines if pvrtc texture compression is supported */
  106. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  107. /** Defines if etc1 texture compression is supported */
  108. public etc1: any; //WEBGL_compressed_texture_etc1;
  109. /** Defines if etc2 texture compression is supported */
  110. public etc2: any; //WEBGL_compressed_texture_etc;
  111. /** Defines if astc texture compression is supported */
  112. public astc: any; //WEBGL_compressed_texture_astc;
  113. /** Defines if float textures are supported */
  114. public textureFloat: boolean;
  115. /** Defines if vertex array objects are supported */
  116. public vertexArrayObject: boolean;
  117. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  118. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  119. /** Gets the maximum level of anisotropy supported */
  120. public maxAnisotropy: number;
  121. /** Defines if instancing is supported */
  122. public instancedArrays: boolean;
  123. /** Defines if 32 bits indices are supported */
  124. public uintIndices: boolean;
  125. /** Defines if high precision shaders are supported */
  126. public highPrecisionShaderSupported: boolean;
  127. /** Defines if depth reading in the fragment shader is supported */
  128. public fragmentDepthSupported: boolean;
  129. /** Defines if float texture linear filtering is supported*/
  130. public textureFloatLinearFiltering: boolean;
  131. /** Defines if rendering to float textures is supported */
  132. public textureFloatRender: boolean;
  133. /** Defines if half float textures are supported*/
  134. public textureHalfFloat: boolean;
  135. /** Defines if half float texture linear filtering is supported*/
  136. public textureHalfFloatLinearFiltering: boolean;
  137. /** Defines if rendering to half float textures is supported */
  138. public textureHalfFloatRender: boolean;
  139. /** Defines if textureLOD shader command is supported */
  140. public textureLOD: boolean;
  141. /** Defines if draw buffers extension is supported */
  142. public drawBuffersExtension: boolean;
  143. /** Defines if depth textures are supported */
  144. public depthTextureExtension: boolean;
  145. /** Defines if float color buffer are supported */
  146. public colorBufferFloat: boolean;
  147. /** Gets disjoint timer query extension (null if not supported) */
  148. public timerQuery: EXT_disjoint_timer_query;
  149. /** Defines if timestamp can be used with timer query */
  150. public canUseTimestampForTimerQuery: boolean;
  151. }
  152. /** Interface defining initialization parameters for Engine class */
  153. export interface EngineOptions extends WebGLContextAttributes {
  154. /**
  155. * Defines if the engine should no exceed a specified device ratio
  156. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  157. */
  158. limitDeviceRatio?: number;
  159. /**
  160. * Defines if webvr should be enabled automatically
  161. * @see http://doc.babylonjs.com/how_to/webvr_camera
  162. */
  163. autoEnableWebVR?: boolean;
  164. /**
  165. * Defines if webgl2 should be turned off even if supported
  166. * @see http://doc.babylonjs.com/features/webgl2
  167. */
  168. disableWebGL2Support?: boolean;
  169. /**
  170. * Defines if webaudio should be initialized as well
  171. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  172. */
  173. audioEngine?: boolean;
  174. /**
  175. * Defines if animations should run using a deterministic lock step
  176. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  177. */
  178. deterministicLockstep?: boolean;
  179. /** Defines the maximum steps to use with deterministic lock step mode */
  180. lockstepMaxSteps?: number;
  181. /**
  182. * Defines that engine should ignore context lost events
  183. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  184. */
  185. doNotHandleContextLost?: boolean;
  186. }
  187. /**
  188. * Defines the interface used by display changed events
  189. */
  190. export interface IDisplayChangedEventArgs {
  191. /** Gets the vrDisplay object (if any) */
  192. vrDisplay: Nullable<any>;
  193. /** Gets a boolean indicating if webVR is supported */
  194. vrSupported: boolean;
  195. }
  196. /**
  197. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  198. */
  199. export class Engine {
  200. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  201. public static ExceptionList = [
  202. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  203. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  204. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  205. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  206. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  207. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  208. ];
  209. /** Gets the list of created engines */
  210. public static Instances = new Array<Engine>();
  211. /**
  212. * Gets the latest created engine
  213. */
  214. public static get LastCreatedEngine(): Nullable<Engine> {
  215. if (Engine.Instances.length === 0) {
  216. return null;
  217. }
  218. return Engine.Instances[Engine.Instances.length - 1];
  219. }
  220. /**
  221. * Gets the latest created scene
  222. */
  223. public static get LastCreatedScene(): Nullable<Scene> {
  224. var lastCreatedEngine = Engine.LastCreatedEngine;
  225. if (!lastCreatedEngine) {
  226. return null;
  227. }
  228. if (lastCreatedEngine.scenes.length === 0) {
  229. return null;
  230. }
  231. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  232. }
  233. /**
  234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  235. * @param flag defines which part of the materials must be marked as dirty
  236. * @param predicate defines a predicate used to filter which materials should be affected
  237. */
  238. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  239. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  240. var engine = Engine.Instances[engineIndex];
  241. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  242. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  243. }
  244. }
  245. }
  246. /**
  247. * Hidden
  248. */
  249. public static _TextureLoaders: IInternalTextureLoader[] = [];
  250. // Const statics
  251. /** Defines that alpha blending is disabled */
  252. public static readonly ALPHA_DISABLE = 0;
  253. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  254. public static readonly ALPHA_ADD = 1;
  255. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  256. public static readonly ALPHA_COMBINE = 2;
  257. /** Defines that alpha blending to DEST - SRC * DEST */
  258. public static readonly ALPHA_SUBTRACT = 3;
  259. /** Defines that alpha blending to SRC * DEST */
  260. public static readonly ALPHA_MULTIPLY = 4;
  261. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  262. public static readonly ALPHA_MAXIMIZED = 5;
  263. /** Defines that alpha blending to SRC + DEST */
  264. public static readonly ALPHA_ONEONE = 6;
  265. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  266. public static readonly ALPHA_PREMULTIPLIED = 7;
  267. /**
  268. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  269. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  270. */
  271. public static readonly ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  272. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  273. public static readonly ALPHA_INTERPOLATE = 9;
  274. /**
  275. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  276. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  277. */
  278. public static readonly ALPHA_SCREENMODE = 10;
  279. /** Defines that the ressource is not delayed*/
  280. public static readonly DELAYLOADSTATE_NONE = 0;
  281. /** Defines that the ressource was successfully delay loaded */
  282. public static readonly DELAYLOADSTATE_LOADED = 1;
  283. /** Defines that the ressource is currently delay loading */
  284. public static readonly DELAYLOADSTATE_LOADING = 2;
  285. /** Defines that the ressource is delayed and has not started loading */
  286. public static readonly DELAYLOADSTATE_NOTLOADED = 4;
  287. // Depht or Stencil test Constants.
  288. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  289. public static readonly NEVER = 0x0200;
  290. /** 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 */
  291. public static readonly ALWAYS = 0x0207;
  292. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  293. public static readonly LESS = 0x0201;
  294. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  295. public static readonly EQUAL = 0x0202;
  296. /** 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 */
  297. public static readonly LEQUAL = 0x0203;
  298. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  299. public static readonly GREATER = 0x0204;
  300. /** 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 */
  301. public static readonly GEQUAL = 0x0206;
  302. /** 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 */
  303. public static readonly NOTEQUAL = 0x0205;
  304. // Stencil Actions Constants.
  305. /** Passed to stencilOperation to specify that stencil value must be kept */
  306. public static readonly KEEP = 0x1E00;
  307. /** Passed to stencilOperation to specify that stencil value must be replaced */
  308. public static readonly REPLACE = 0x1E01;
  309. /** Passed to stencilOperation to specify that stencil value must be incremented */
  310. public static readonly INCR = 0x1E02;
  311. /** Passed to stencilOperation to specify that stencil value must be decremented */
  312. public static readonly DECR = 0x1E03;
  313. /** Passed to stencilOperation to specify that stencil value must be inverted */
  314. public static readonly INVERT = 0x150A;
  315. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  316. public static readonly INCR_WRAP = 0x8507;
  317. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  318. public static readonly DECR_WRAP = 0x8508;
  319. /** Texture is not repeating outside of 0..1 UVs */
  320. public static readonly TEXTURE_CLAMP_ADDRESSMODE = 0;
  321. /** Texture is repeating outside of 0..1 UVs */
  322. public static readonly TEXTURE_WRAP_ADDRESSMODE = 1;
  323. /** Texture is repeating and mirrored */
  324. public static readonly TEXTURE_MIRROR_ADDRESSMODE = 2;
  325. /** ALPHA */
  326. public static readonly TEXTUREFORMAT_ALPHA = 0;
  327. /** LUMINANCE */
  328. public static readonly TEXTUREFORMAT_LUMINANCE = 1;
  329. /** LUMINANCE_ALPHA */
  330. public static readonly TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  331. /** RGB */
  332. public static readonly TEXTUREFORMAT_RGB = 4;
  333. /** RGBA */
  334. public static readonly TEXTUREFORMAT_RGBA = 5;
  335. /** RED */
  336. public static readonly TEXTUREFORMAT_RED = 6;
  337. /** RED (2nd reference) */
  338. public static readonly TEXTUREFORMAT_R = 6;
  339. /** RG */
  340. public static readonly TEXTUREFORMAT_RG = 7;
  341. /** RED_INTEGER */
  342. public static readonly TEXTUREFORMAT_RED_INTEGER = 8;
  343. /** RED_INTEGER (2nd reference) */
  344. public static readonly TEXTUREFORMAT_R_INTEGER = 8;
  345. /** RG_INTEGER */
  346. public static readonly TEXTUREFORMAT_RG_INTEGER = 9;
  347. /** RGB_INTEGER */
  348. public static readonly TEXTUREFORMAT_RGB_INTEGER = 10;
  349. /** RGBA_INTEGER */
  350. public static readonly TEXTUREFORMAT_RGBA_INTEGER = 11;
  351. /** UNSIGNED_BYTE */
  352. public static readonly TEXTURETYPE_UNSIGNED_BYTE = 0;
  353. /** UNSIGNED_BYTE (2nd reference) */
  354. public static readonly TEXTURETYPE_UNSIGNED_INT = 0;
  355. /** FLOAT */
  356. public static readonly TEXTURETYPE_FLOAT = 1;
  357. /** HALF_FLOAT */
  358. public static readonly TEXTURETYPE_HALF_FLOAT = 2;
  359. /** BYTE */
  360. public static readonly TEXTURETYPE_BYTE = 3;
  361. /** SHORT */
  362. public static readonly TEXTURETYPE_SHORT = 4;
  363. /** UNSIGNED_SHORT */
  364. public static readonly TEXTURETYPE_UNSIGNED_SHORT = 5;
  365. /** INT */
  366. public static readonly TEXTURETYPE_INT = 6;
  367. /** UNSIGNED_INT */
  368. public static readonly TEXTURETYPE_UNSIGNED_INTEGER = 7;
  369. /** UNSIGNED_SHORT_4_4_4_4 */
  370. public static readonly TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  371. /** UNSIGNED_SHORT_5_5_5_1 */
  372. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  373. /** UNSIGNED_SHORT_5_6_5 */
  374. public static readonly TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  375. /** UNSIGNED_INT_2_10_10_10_REV */
  376. public static readonly TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  377. /** UNSIGNED_INT_24_8 */
  378. public static readonly TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  379. /** UNSIGNED_INT_10F_11F_11F_REV */
  380. public static readonly TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  381. /** UNSIGNED_INT_5_9_9_9_REV */
  382. public static readonly TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  383. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  384. public static readonly TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  385. /** nearest is mag = nearest and min = nearest and mip = linear */
  386. public static readonly TEXTURE_NEAREST_SAMPLINGMODE = 1;
  387. /** Bilinear is mag = linear and min = linear and mip = nearest */
  388. public static readonly TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  389. /** Trilinear is mag = linear and min = linear and mip = linear */
  390. public static readonly TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  391. /** nearest is mag = nearest and min = nearest and mip = linear */
  392. public static readonly TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  393. /** Bilinear is mag = linear and min = linear and mip = nearest */
  394. public static readonly TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  395. /** Trilinear is mag = linear and min = linear and mip = linear */
  396. public static readonly TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  397. /** mag = nearest and min = nearest and mip = nearest */
  398. public static readonly TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  399. /** mag = nearest and min = linear and mip = nearest */
  400. public static readonly TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  401. /** mag = nearest and min = linear and mip = linear */
  402. public static readonly TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  403. /** mag = nearest and min = linear and mip = none */
  404. public static readonly TEXTURE_NEAREST_LINEAR = 7;
  405. /** mag = nearest and min = nearest and mip = none */
  406. public static readonly TEXTURE_NEAREST_NEAREST = 8;
  407. /** mag = linear and min = nearest and mip = nearest */
  408. public static readonly TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  409. /** mag = linear and min = nearest and mip = linear */
  410. public static readonly TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  411. /** mag = linear and min = linear and mip = none */
  412. public static readonly TEXTURE_LINEAR_LINEAR = 11;
  413. /** mag = linear and min = nearest and mip = none */
  414. public static readonly TEXTURE_LINEAR_NEAREST = 12;
  415. /** Explicit coordinates mode */
  416. public static readonly TEXTURE_EXPLICIT_MODE = 0;
  417. /** Spherical coordinates mode */
  418. public static readonly TEXTURE_SPHERICAL_MODE = 1;
  419. /** Planar coordinates mode */
  420. public static readonly TEXTURE_PLANAR_MODE = 2;
  421. /** Cubic coordinates mode */
  422. public static readonly TEXTURE_CUBIC_MODE = 3;
  423. /** Projection coordinates mode */
  424. public static readonly TEXTURE_PROJECTION_MODE = 4;
  425. /** Skybox coordinates mode */
  426. public static readonly TEXTURE_SKYBOX_MODE = 5;
  427. /** Inverse Cubic coordinates mode */
  428. public static readonly TEXTURE_INVCUBIC_MODE = 6;
  429. /** Equirectangular coordinates mode */
  430. public static readonly TEXTURE_EQUIRECTANGULAR_MODE = 7;
  431. /** Equirectangular Fixed coordinates mode */
  432. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  433. /** Equirectangular Fixed Mirrored coordinates mode */
  434. public static readonly TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  435. // Texture rescaling mode
  436. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  437. public static readonly SCALEMODE_FLOOR = 1;
  438. /** Defines that texture rescaling will look for the nearest power of 2 size */
  439. public static readonly SCALEMODE_NEAREST = 2;
  440. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  441. public static readonly SCALEMODE_CEILING = 3;
  442. /**
  443. * Returns the current version of the framework
  444. */
  445. public static get Version(): string {
  446. return "3.3.0-beta.4";
  447. }
  448. // Updatable statics so stick with vars here
  449. /**
  450. * Gets or sets the epsilon value used by collision engine
  451. */
  452. public static CollisionsEpsilon = 0.001;
  453. /**
  454. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  455. */
  456. public static CodeRepository = "src/";
  457. /**
  458. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  459. */
  460. public static ShadersRepository = "src/Shaders/";
  461. // Public members
  462. /**
  463. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  464. */
  465. public forcePOTTextures = false;
  466. /**
  467. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  468. */
  469. public isFullscreen = false;
  470. /**
  471. * Gets a boolean indicating if the pointer is currently locked
  472. */
  473. public isPointerLock = false;
  474. /**
  475. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  476. */
  477. public cullBackFaces = true;
  478. /**
  479. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  480. */
  481. public renderEvenInBackground = true;
  482. /**
  483. * Gets or sets a boolean indicating that cache can be kept between frames
  484. */
  485. public preventCacheWipeBetweenFrames = false;
  486. /**
  487. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  488. **/
  489. public enableOfflineSupport = false;
  490. /**
  491. * 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)
  492. **/
  493. public disableManifestCheck = false;
  494. /**
  495. * Gets the list of created scenes
  496. */
  497. public scenes = new Array<Scene>();
  498. /**
  499. * Gets the list of created postprocesses
  500. */
  501. public postProcesses = new Array<PostProcess>();
  502. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  503. public validateShaderPrograms = false;
  504. // Observables
  505. /**
  506. * Observable event triggered each time the rendering canvas is resized
  507. */
  508. public onResizeObservable = new Observable<Engine>();
  509. /**
  510. * Observable event triggered each time the canvas loses focus
  511. */
  512. public onCanvasBlurObservable = new Observable<Engine>();
  513. /**
  514. * Observable event triggered each time the canvas gains focus
  515. */
  516. public onCanvasFocusObservable = new Observable<Engine>();
  517. /**
  518. * Observable event triggered each time the canvas receives pointerout event
  519. */
  520. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  521. /**
  522. * Observable event triggered before each texture is initialized
  523. */
  524. public onBeforeTextureInitObservable = new Observable<Texture>();
  525. //WebVR
  526. private _vrDisplay: any = undefined;
  527. private _vrSupported: boolean = false;
  528. private _oldSize: Size;
  529. private _oldHardwareScaleFactor: number;
  530. private _vrExclusivePointerMode = false;
  531. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  532. /**
  533. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  534. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  535. */
  536. public get isInVRExclusivePointerMode(): boolean {
  537. return this._vrExclusivePointerMode;
  538. }
  539. // Uniform buffers list
  540. /**
  541. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  542. */
  543. public disableUniformBuffers = false;
  544. /** @hidden */
  545. public _uniformBuffers = new Array<UniformBuffer>();
  546. /**
  547. * Gets a boolean indicating that the engine supports uniform buffers
  548. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  549. */
  550. public get supportsUniformBuffers(): boolean {
  551. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  552. }
  553. // Observables
  554. /**
  555. * Observable raised when the engine begins a new frame
  556. */
  557. public onBeginFrameObservable = new Observable<Engine>();
  558. /**
  559. * Observable raised when the engine ends the current frame
  560. */
  561. public onEndFrameObservable = new Observable<Engine>();
  562. /**
  563. * Observable raised when the engine is about to compile a shader
  564. */
  565. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  566. /**
  567. * Observable raised when the engine has jsut compiled a shader
  568. */
  569. public onAfterShaderCompilationObservable = new Observable<Engine>();
  570. // Private Members
  571. /** @hidden */
  572. public _gl: WebGLRenderingContext;
  573. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  574. private _windowIsBackground = false;
  575. private _webGLVersion = 1.0;
  576. /**
  577. * Gets a boolean indicating that only power of 2 textures are supported
  578. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  579. */
  580. public get needPOTTextures(): boolean {
  581. return this._webGLVersion < 2 || this.forcePOTTextures;
  582. }
  583. /** @hidden */
  584. public _badOS = false;
  585. /** @hidden */
  586. public _badDesktopOS = false;
  587. /**
  588. * Gets or sets a value indicating if we want to disable texture binding optmization.
  589. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  590. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  591. */
  592. public disableTextureBindingOptimization = false;
  593. /**
  594. * Gets the audio engine
  595. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  596. * @ignorenaming
  597. */
  598. public static audioEngine: AudioEngine;
  599. // Focus
  600. private _onFocus: () => void;
  601. private _onBlur: () => void;
  602. private _onCanvasPointerOut: (event: PointerEvent) => void;
  603. private _onCanvasBlur: () => void;
  604. private _onCanvasFocus: () => void;
  605. private _onFullscreenChange: () => void;
  606. private _onPointerLockChange: () => void;
  607. private _onVRDisplayPointerRestricted: () => void;
  608. private _onVRDisplayPointerUnrestricted: () => void;
  609. // VRDisplay connection
  610. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  611. private _onVrDisplayDisconnect: Nullable<() => void>;
  612. private _onVrDisplayPresentChange: Nullable<() => void>;
  613. /**
  614. * Observable signaled when VR display mode changes
  615. */
  616. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  617. /**
  618. * Observable signaled when VR request present is complete
  619. */
  620. public onVRRequestPresentComplete = new Observable<boolean>();
  621. /**
  622. * Observable signaled when VR request present starts
  623. */
  624. public onVRRequestPresentStart = new Observable<Engine>();
  625. private _hardwareScalingLevel: number;
  626. /** @hidden */
  627. protected _caps: EngineCapabilities;
  628. private _pointerLockRequested: boolean;
  629. private _isStencilEnable: boolean;
  630. private _colorWrite = true;
  631. private _loadingScreen: ILoadingScreen;
  632. /** @hidden */
  633. public _drawCalls = new PerfCounter();
  634. /** @hidden */
  635. public _textureCollisions = new PerfCounter();
  636. private _glVersion: string;
  637. private _glRenderer: string;
  638. private _glVendor: string;
  639. private _videoTextureSupported: boolean;
  640. private _renderingQueueLaunched = false;
  641. private _activeRenderLoops = new Array<() => void>();
  642. // Deterministic lockstepMaxSteps
  643. private _deterministicLockstep: boolean = false;
  644. private _lockstepMaxSteps: number = 4;
  645. // Lost context
  646. /**
  647. * Observable signaled when a context lost event is raised
  648. */
  649. public onContextLostObservable = new Observable<Engine>();
  650. /**
  651. * Observable signaled when a context restored event is raised
  652. */
  653. public onContextRestoredObservable = new Observable<Engine>();
  654. private _onContextLost: (evt: Event) => void;
  655. private _onContextRestored: (evt: Event) => void;
  656. private _contextWasLost = false;
  657. private _doNotHandleContextLost = false;
  658. /**
  659. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  660. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  661. */
  662. public get doNotHandleContextLost(): boolean {
  663. return this._doNotHandleContextLost;
  664. }
  665. public set doNotHandleContextLost(value: boolean) {
  666. this._doNotHandleContextLost = value;
  667. }
  668. // FPS
  669. private _performanceMonitor = new PerformanceMonitor();
  670. private _fps = 60;
  671. private _deltaTime = 0;
  672. /**
  673. * Turn this value on if you want to pause FPS computation when in background
  674. */
  675. public disablePerformanceMonitorInBackground = false;
  676. /**
  677. * Gets the performance monitor attached to this engine
  678. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  679. */
  680. public get performanceMonitor(): PerformanceMonitor {
  681. return this._performanceMonitor;
  682. }
  683. // States
  684. /** @hidden */
  685. protected _depthCullingState = new _DepthCullingState();
  686. /** @hidden */
  687. protected _stencilState = new _StencilState();
  688. /** @hidden */
  689. protected _alphaState = new _AlphaState();
  690. /** @hidden */
  691. protected _alphaMode = Engine.ALPHA_DISABLE;
  692. // Cache
  693. protected _internalTexturesCache = new Array<InternalTexture>();
  694. /** @hidden */
  695. protected _activeChannel = 0;
  696. private _currentTextureChannel = -1;
  697. /** @hidden */
  698. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  699. /** @hidden */
  700. protected _currentEffect: Nullable<Effect>;
  701. /** @hidden */
  702. protected _currentProgram: Nullable<WebGLProgram>;
  703. private _compiledEffects: { [key: string]: Effect } = {}
  704. private _vertexAttribArraysEnabled: boolean[] = [];
  705. /** @hidden */
  706. protected _cachedViewport: Nullable<Viewport>;
  707. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  708. /** @hidden */
  709. protected _cachedVertexBuffers: any;
  710. /** @hidden */
  711. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  712. /** @hidden */
  713. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  714. /** @hidden */
  715. protected _currentRenderTarget: Nullable<InternalTexture>;
  716. private _uintIndicesCurrentlySet = false;
  717. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  718. /** @hidden */
  719. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  720. private _currentBufferPointers = new Array<BufferPointer>();
  721. private _currentInstanceLocations = new Array<number>();
  722. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  723. private _textureUnits: Int32Array;
  724. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  725. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  726. private _workingCanvas: Nullable<HTMLCanvasElement>;
  727. private _workingContext: Nullable<CanvasRenderingContext2D>;
  728. private _rescalePostProcess: PassPostProcess;
  729. private _dummyFramebuffer: WebGLFramebuffer;
  730. private _externalData: StringDictionary<Object>;
  731. private _bindedRenderFunction: any;
  732. private _vaoRecordInProgress = false;
  733. private _mustWipeVertexAttributes = false;
  734. private _emptyTexture: Nullable<InternalTexture>;
  735. private _emptyCubeTexture: Nullable<InternalTexture>;
  736. private _emptyTexture3D: Nullable<InternalTexture>;
  737. private _frameHandler: number;
  738. private _nextFreeTextureSlots = new Array<number>();
  739. private _maxSimultaneousTextures = 0;
  740. private _activeRequests = new Array<IFileRequest>();
  741. // Hardware supported Compressed Textures
  742. private _texturesSupported = new Array<string>();
  743. private _textureFormatInUse: Nullable<string>;
  744. /**
  745. * Gets the list of texture formats supported
  746. */
  747. public get texturesSupported(): Array<string> {
  748. return this._texturesSupported;
  749. }
  750. /**
  751. * Gets the list of texture formats in use
  752. */
  753. public get textureFormatInUse(): Nullable<string> {
  754. return this._textureFormatInUse;
  755. }
  756. /**
  757. * Gets the current viewport
  758. */
  759. public get currentViewport(): Nullable<Viewport> {
  760. return this._cachedViewport;
  761. }
  762. /**
  763. * Gets the default empty texture
  764. */
  765. public get emptyTexture(): InternalTexture {
  766. if (!this._emptyTexture) {
  767. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  768. }
  769. return this._emptyTexture;
  770. }
  771. /**
  772. * Gets the default empty 3D texture
  773. */
  774. public get emptyTexture3D(): InternalTexture {
  775. if (!this._emptyTexture3D) {
  776. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  777. }
  778. return this._emptyTexture3D;
  779. }
  780. /**
  781. * Gets the default empty cube texture
  782. */
  783. public get emptyCubeTexture(): InternalTexture {
  784. if (!this._emptyCubeTexture) {
  785. var faceData = new Uint8Array(4);
  786. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  787. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  788. }
  789. return this._emptyCubeTexture;
  790. }
  791. /**
  792. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  793. */
  794. public readonly premultipliedAlpha: boolean = true;
  795. /**
  796. * Creates a new engine
  797. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  798. * @param antialias defines enable antialiasing (default: false)
  799. * @param options defines further options to be sent to the getContext() function
  800. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  801. */
  802. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  803. // Register promises
  804. PromisePolyfill.Apply();
  805. let canvas: Nullable<HTMLCanvasElement> = null;
  806. Engine.Instances.push(this);
  807. if (!canvasOrContext) {
  808. return;
  809. }
  810. options = options || {};
  811. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  812. canvas = <HTMLCanvasElement>canvasOrContext;
  813. this._renderingCanvas = canvas;
  814. if (antialias != null) {
  815. options.antialias = antialias;
  816. }
  817. if (options.deterministicLockstep === undefined) {
  818. options.deterministicLockstep = false;
  819. }
  820. if (options.lockstepMaxSteps === undefined) {
  821. options.lockstepMaxSteps = 4;
  822. }
  823. if (options.preserveDrawingBuffer === undefined) {
  824. options.preserveDrawingBuffer = false;
  825. }
  826. if (options.audioEngine === undefined) {
  827. options.audioEngine = true;
  828. }
  829. if (options.stencil === undefined) {
  830. options.stencil = true;
  831. }
  832. if (options.premultipliedAlpha === false) {
  833. this.premultipliedAlpha = false;
  834. }
  835. this._deterministicLockstep = options.deterministicLockstep;
  836. this._lockstepMaxSteps = options.lockstepMaxSteps;
  837. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  838. // Exceptions
  839. if (navigator && navigator.userAgent) {
  840. let ua = navigator.userAgent;
  841. for (var exception of Engine.ExceptionList) {
  842. let key = exception.key;
  843. let targets = exception.targets;
  844. if (ua.indexOf(key) > -1) {
  845. if (exception.capture && exception.captureConstraint) {
  846. let capture = exception.capture;
  847. let constraint = exception.captureConstraint;
  848. let regex = new RegExp(capture);
  849. let matches = regex.exec(ua);
  850. if (matches && matches.length > 0) {
  851. let capturedValue = parseInt(matches[matches.length - 1]);
  852. if (capturedValue >= constraint) {
  853. continue;
  854. }
  855. }
  856. }
  857. for (var target of targets) {
  858. switch (target) {
  859. case "uniformBuffer":
  860. this.disableUniformBuffers = true;
  861. break;
  862. case "textureBindingOptimization":
  863. this.disableTextureBindingOptimization = true;
  864. break;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. // GL
  871. if (!options.disableWebGL2Support) {
  872. try {
  873. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  874. if (this._gl) {
  875. this._webGLVersion = 2.0;
  876. }
  877. } catch (e) {
  878. // Do nothing
  879. }
  880. }
  881. if (!this._gl) {
  882. if (!canvas) {
  883. throw new Error("The provided canvas is null or undefined.");
  884. }
  885. try {
  886. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  887. } catch (e) {
  888. throw new Error("WebGL not supported");
  889. }
  890. }
  891. if (!this._gl) {
  892. throw new Error("WebGL not supported");
  893. }
  894. this._onCanvasFocus = () => {
  895. this.onCanvasFocusObservable.notifyObservers(this);
  896. }
  897. this._onCanvasBlur = () => {
  898. this.onCanvasBlurObservable.notifyObservers(this);
  899. }
  900. canvas.addEventListener("focus", this._onCanvasFocus);
  901. canvas.addEventListener("blur", this._onCanvasBlur);
  902. this._onBlur = () => {
  903. if (this.disablePerformanceMonitorInBackground) {
  904. this._performanceMonitor.disable();
  905. }
  906. this._windowIsBackground = true;
  907. };
  908. this._onFocus = () => {
  909. if (this.disablePerformanceMonitorInBackground) {
  910. this._performanceMonitor.enable();
  911. }
  912. this._windowIsBackground = false;
  913. };
  914. this._onCanvasPointerOut = (ev) => {
  915. this.onCanvasPointerOutObservable.notifyObservers(ev);
  916. };
  917. window.addEventListener("blur", this._onBlur);
  918. window.addEventListener("focus", this._onFocus);
  919. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  920. // Context lost
  921. if (!this._doNotHandleContextLost) {
  922. this._onContextLost = (evt: Event) => {
  923. evt.preventDefault();
  924. this._contextWasLost = true;
  925. Tools.Warn("WebGL context lost.");
  926. this.onContextLostObservable.notifyObservers(this);
  927. };
  928. this._onContextRestored = (evt: Event) => {
  929. // Adding a timeout to avoid race condition at browser level
  930. setTimeout(() => {
  931. // Rebuild gl context
  932. this._initGLContext();
  933. // Rebuild effects
  934. this._rebuildEffects();
  935. // Rebuild textures
  936. this._rebuildInternalTextures();
  937. // Rebuild buffers
  938. this._rebuildBuffers();
  939. // Cache
  940. this.wipeCaches(true);
  941. Tools.Warn("WebGL context successfully restored.");
  942. this.onContextRestoredObservable.notifyObservers(this);
  943. this._contextWasLost = false;
  944. }, 0);
  945. };
  946. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  947. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  948. }
  949. } else {
  950. this._gl = <WebGLRenderingContext>canvasOrContext;
  951. this._renderingCanvas = this._gl.canvas
  952. if (this._gl.renderbufferStorageMultisample) {
  953. this._webGLVersion = 2.0;
  954. }
  955. options.stencil = this._gl.getContextAttributes().stencil;
  956. }
  957. // Viewport
  958. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  959. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  960. this.resize();
  961. this._isStencilEnable = options.stencil ? true : false;
  962. this._initGLContext();
  963. if (canvas) {
  964. // Fullscreen
  965. this._onFullscreenChange = () => {
  966. if (document.fullscreen !== undefined) {
  967. this.isFullscreen = document.fullscreen;
  968. } else if (document.mozFullScreen !== undefined) {
  969. this.isFullscreen = document.mozFullScreen;
  970. } else if (document.webkitIsFullScreen !== undefined) {
  971. this.isFullscreen = document.webkitIsFullScreen;
  972. } else if (document.msIsFullScreen !== undefined) {
  973. this.isFullscreen = document.msIsFullScreen;
  974. }
  975. // Pointer lock
  976. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  977. canvas.requestPointerLock = canvas.requestPointerLock ||
  978. canvas.msRequestPointerLock ||
  979. canvas.mozRequestPointerLock ||
  980. canvas.webkitRequestPointerLock;
  981. if (canvas.requestPointerLock) {
  982. canvas.requestPointerLock();
  983. }
  984. }
  985. };
  986. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  987. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  988. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  989. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  990. // Pointer lock
  991. this._onPointerLockChange = () => {
  992. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  993. document.webkitPointerLockElement === canvas ||
  994. document.msPointerLockElement === canvas ||
  995. document.pointerLockElement === canvas
  996. );
  997. };
  998. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  999. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1000. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1001. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1002. this._onVRDisplayPointerRestricted = () => {
  1003. if (canvas) {
  1004. canvas.requestPointerLock();
  1005. }
  1006. }
  1007. this._onVRDisplayPointerUnrestricted = () => {
  1008. document.exitPointerLock();
  1009. }
  1010. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1011. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1012. }
  1013. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  1014. Engine.audioEngine = new AudioEngine();
  1015. }
  1016. // Prepare buffer pointers
  1017. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1018. this._currentBufferPointers[i] = new BufferPointer();
  1019. }
  1020. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1021. // Load WebVR Devices
  1022. if (options.autoEnableWebVR) {
  1023. this.initWebVR();
  1024. }
  1025. // Detect if we are running on a faulty buggy OS.
  1026. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1027. // Detect if we are running on a faulty buggy desktop OS.
  1028. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1029. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  1030. this.enableOfflineSupport = (Database !== undefined);
  1031. }
  1032. private _rebuildInternalTextures(): void {
  1033. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1034. for (var internalTexture of currentState) {
  1035. internalTexture._rebuild();
  1036. }
  1037. }
  1038. private _rebuildEffects(): void {
  1039. for (var key in this._compiledEffects) {
  1040. let effect = <Effect>this._compiledEffects[key];
  1041. effect._prepareEffect();
  1042. }
  1043. Effect.ResetCache();
  1044. }
  1045. private _rebuildBuffers(): void {
  1046. // Index / Vertex
  1047. for (var scene of this.scenes) {
  1048. scene.resetCachedMaterial();
  1049. scene._rebuildGeometries();
  1050. scene._rebuildTextures();
  1051. }
  1052. // Uniforms
  1053. for (var uniformBuffer of this._uniformBuffers) {
  1054. uniformBuffer._rebuild();
  1055. }
  1056. }
  1057. private _initGLContext(): void {
  1058. // Caps
  1059. this._caps = new EngineCapabilities();
  1060. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1061. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1062. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1063. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1064. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1065. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1066. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1067. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1068. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1069. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1070. // Infos
  1071. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1072. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1073. if (rendererInfo != null) {
  1074. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1075. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1076. }
  1077. if (!this._glVendor) {
  1078. this._glVendor = "Unknown vendor";
  1079. }
  1080. if (!this._glRenderer) {
  1081. this._glRenderer = "Unknown renderer";
  1082. }
  1083. // Constants
  1084. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1085. if (this._gl.RGBA16F !== 0x881A) {
  1086. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1087. }
  1088. if (this._gl.RGBA32F !== 0x8814) {
  1089. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1090. }
  1091. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1092. this._gl.DEPTH24_STENCIL8 = 35056;
  1093. }
  1094. // Extensions
  1095. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1096. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1097. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1098. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1099. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1100. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1101. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1102. 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');
  1103. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1104. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1105. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1106. this._caps.highPrecisionShaderSupported = true;
  1107. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1108. if (this._caps.timerQuery) {
  1109. if (this._webGLVersion === 1) {
  1110. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1111. }
  1112. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1113. }
  1114. // Checks if some of the format renders first to allow the use of webgl inspector.
  1115. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1116. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1117. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1118. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true: false;
  1119. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true: false;
  1120. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1121. if (this._webGLVersion > 1) {
  1122. this._gl.HALF_FLOAT_OES = 0x140B;
  1123. }
  1124. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1125. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true: false;
  1126. // Draw buffers
  1127. if (this._webGLVersion > 1) {
  1128. this._caps.drawBuffersExtension = true;
  1129. } else {
  1130. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1131. if (drawBuffersExtension !== null) {
  1132. this._caps.drawBuffersExtension = true;
  1133. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1134. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1135. for (var i = 0; i < 16; i++) {
  1136. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1137. }
  1138. } else {
  1139. this._caps.drawBuffersExtension = false;
  1140. }
  1141. }
  1142. // Depth Texture
  1143. if (this._webGLVersion > 1) {
  1144. this._caps.depthTextureExtension = true;
  1145. } else {
  1146. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1147. if (depthTextureExtension != null) {
  1148. this._caps.depthTextureExtension = true;
  1149. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1150. }
  1151. }
  1152. // Vertex array object
  1153. if (this._webGLVersion > 1) {
  1154. this._caps.vertexArrayObject = true;
  1155. } else {
  1156. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1157. if (vertexArrayObjectExtension != null) {
  1158. this._caps.vertexArrayObject = true;
  1159. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1160. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1161. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1162. } else {
  1163. this._caps.vertexArrayObject = false;
  1164. }
  1165. }
  1166. // Instances count
  1167. if (this._webGLVersion > 1) {
  1168. this._caps.instancedArrays = true;
  1169. } else {
  1170. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1171. if (instanceExtension != null) {
  1172. this._caps.instancedArrays = true;
  1173. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1174. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1175. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1176. } else {
  1177. this._caps.instancedArrays = false;
  1178. }
  1179. }
  1180. // Intelligently add supported compressed formats in order to check for.
  1181. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1182. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1183. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1184. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1185. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1186. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1187. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1188. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1189. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1190. if (this._gl.getShaderPrecisionFormat) {
  1191. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1192. if (highp) {
  1193. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1194. }
  1195. }
  1196. // Depth buffer
  1197. this.setDepthBuffer(true);
  1198. this.setDepthFunctionToLessOrEqual();
  1199. this.setDepthWrite(true);
  1200. // Texture maps
  1201. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1202. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1203. this._nextFreeTextureSlots.push(slot);
  1204. }
  1205. }
  1206. /**
  1207. * Gets version of the current webGL context
  1208. */
  1209. public get webGLVersion(): number {
  1210. return this._webGLVersion;
  1211. }
  1212. /**
  1213. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1214. */
  1215. public get isStencilEnable(): boolean {
  1216. return this._isStencilEnable;
  1217. }
  1218. private _prepareWorkingCanvas(): void {
  1219. if (this._workingCanvas) {
  1220. return;
  1221. }
  1222. this._workingCanvas = document.createElement("canvas");
  1223. let context = this._workingCanvas.getContext("2d");
  1224. if (context) {
  1225. this._workingContext = context;
  1226. }
  1227. }
  1228. /**
  1229. * Reset the texture cache to empty state
  1230. */
  1231. public resetTextureCache() {
  1232. for (var key in this._boundTexturesCache) {
  1233. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1234. continue;
  1235. }
  1236. let boundTexture = this._boundTexturesCache[key];
  1237. if (boundTexture) {
  1238. this._removeDesignatedSlot(boundTexture);
  1239. }
  1240. this._boundTexturesCache[key] = null;
  1241. }
  1242. if (!this.disableTextureBindingOptimization) {
  1243. this._nextFreeTextureSlots = [];
  1244. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1245. this._nextFreeTextureSlots.push(slot);
  1246. }
  1247. }
  1248. this._currentTextureChannel = -1;
  1249. }
  1250. /**
  1251. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1252. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1253. * @returns true if engine is in deterministic lock step mode
  1254. */
  1255. public isDeterministicLockStep(): boolean {
  1256. return this._deterministicLockstep;
  1257. }
  1258. /**
  1259. * Gets the max steps when engine is running in deterministic lock step
  1260. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1261. * @returns the max steps
  1262. */
  1263. public getLockstepMaxSteps(): number {
  1264. return this._lockstepMaxSteps;
  1265. }
  1266. /**
  1267. * Gets an object containing information about the current webGL context
  1268. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1269. */
  1270. public getGlInfo() {
  1271. return {
  1272. vendor: this._glVendor,
  1273. renderer: this._glRenderer,
  1274. version: this._glVersion
  1275. }
  1276. }
  1277. /**
  1278. * Gets current aspect ratio
  1279. * @param camera defines the camera to use to get the aspect ratio
  1280. * @param useScreen defines if screen size must be used (or the current render target if any)
  1281. * @returns a number defining the aspect ratio
  1282. */
  1283. public getAspectRatio(camera: Camera, useScreen = false): number {
  1284. var viewport = camera.viewport;
  1285. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1286. }
  1287. /**
  1288. * Gets current screen aspect ratio
  1289. * @returns a number defining the aspect ratio
  1290. */
  1291. public getScreenAspectRatio(): number {
  1292. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1293. }
  1294. /**
  1295. * Gets the current render width
  1296. * @param useScreen defines if screen size must be used (or the current render target if any)
  1297. * @returns a number defining the current render width
  1298. */
  1299. public getRenderWidth(useScreen = false): number {
  1300. if (!useScreen && this._currentRenderTarget) {
  1301. return this._currentRenderTarget.width;
  1302. }
  1303. return this._gl.drawingBufferWidth;
  1304. }
  1305. /**
  1306. * Gets the current render height
  1307. * @param useScreen defines if screen size must be used (or the current render target if any)
  1308. * @returns a number defining the current render height
  1309. */
  1310. public getRenderHeight(useScreen = false): number {
  1311. if (!useScreen && this._currentRenderTarget) {
  1312. return this._currentRenderTarget.height;
  1313. }
  1314. return this._gl.drawingBufferHeight;
  1315. }
  1316. /**
  1317. * Gets the HTML canvas attached with the current webGL context
  1318. * @returns a HTML canvas
  1319. */
  1320. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1321. return this._renderingCanvas;
  1322. }
  1323. /**
  1324. * Gets the client rect of the HTML canvas attached with the current webGL context
  1325. * @returns a client rectanglee
  1326. */
  1327. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1328. if (!this._renderingCanvas) {
  1329. return null;
  1330. }
  1331. return this._renderingCanvas.getBoundingClientRect();
  1332. }
  1333. /**
  1334. * Defines the hardware scaling level.
  1335. * By default the hardware scaling level is computed from the window device ratio.
  1336. * 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.
  1337. * @param level defines the level to use
  1338. */
  1339. public setHardwareScalingLevel(level: number): void {
  1340. this._hardwareScalingLevel = level;
  1341. this.resize();
  1342. }
  1343. /**
  1344. * Gets the current hardware scaling level.
  1345. * By default the hardware scaling level is computed from the window device ratio.
  1346. * 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.
  1347. * @returns a number indicating the current hardware scaling level
  1348. */
  1349. public getHardwareScalingLevel(): number {
  1350. return this._hardwareScalingLevel;
  1351. }
  1352. /**
  1353. * Gets the list of loaded textures
  1354. * @returns an array containing all loaded textures
  1355. */
  1356. public getLoadedTexturesCache(): InternalTexture[] {
  1357. return this._internalTexturesCache;
  1358. }
  1359. /**
  1360. * Gets the object containing all engine capabilities
  1361. * @returns the EngineCapabilities object
  1362. */
  1363. public getCaps(): EngineCapabilities {
  1364. return this._caps;
  1365. }
  1366. /** @hidden */
  1367. public get drawCalls(): number {
  1368. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1369. return 0;
  1370. }
  1371. /** @hidden */
  1372. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1373. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1374. return null;
  1375. }
  1376. /**
  1377. * Gets the current depth function
  1378. * @returns a number defining the depth function
  1379. */
  1380. public getDepthFunction(): Nullable<number> {
  1381. return this._depthCullingState.depthFunc;
  1382. }
  1383. /**
  1384. * Sets the current depth function
  1385. * @param depthFunc defines the function to use
  1386. */
  1387. public setDepthFunction(depthFunc: number) {
  1388. this._depthCullingState.depthFunc = depthFunc;
  1389. }
  1390. /**
  1391. * Sets the current depth function to GREATER
  1392. */
  1393. public setDepthFunctionToGreater(): void {
  1394. this._depthCullingState.depthFunc = this._gl.GREATER;
  1395. }
  1396. /**
  1397. * Sets the current depth function to GEQUAL
  1398. */
  1399. public setDepthFunctionToGreaterOrEqual(): void {
  1400. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1401. }
  1402. /**
  1403. * Sets the current depth function to LESS
  1404. */
  1405. public setDepthFunctionToLess(): void {
  1406. this._depthCullingState.depthFunc = this._gl.LESS;
  1407. }
  1408. /**
  1409. * Sets the current depth function to LEQUAL
  1410. */
  1411. public setDepthFunctionToLessOrEqual(): void {
  1412. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1413. }
  1414. /**
  1415. * Gets a boolean indicating if stencil buffer is enabled
  1416. * @returns the current stencil buffer state
  1417. */
  1418. public getStencilBuffer(): boolean {
  1419. return this._stencilState.stencilTest;
  1420. }
  1421. /**
  1422. * Enable or disable the stencil buffer
  1423. * @param enable defines if the stencil buffer must be enabled or disabled
  1424. */
  1425. public setStencilBuffer(enable: boolean): void {
  1426. this._stencilState.stencilTest = enable;
  1427. }
  1428. /**
  1429. * Gets the current stencil mask
  1430. * @returns a number defining the new stencil mask to use
  1431. */
  1432. public getStencilMask(): number {
  1433. return this._stencilState.stencilMask;
  1434. }
  1435. /**
  1436. * Sets the current stencil mask
  1437. * @param mask defines the new stencil mask to use
  1438. */
  1439. public setStencilMask(mask: number): void {
  1440. this._stencilState.stencilMask = mask;
  1441. }
  1442. /**
  1443. * Gets the current stencil function
  1444. * @returns a number defining the stencil function to use
  1445. */
  1446. public getStencilFunction(): number {
  1447. return this._stencilState.stencilFunc;
  1448. }
  1449. /**
  1450. * Gets the current stencil reference value
  1451. * @returns a number defining the stencil reference value to use
  1452. */
  1453. public getStencilFunctionReference(): number {
  1454. return this._stencilState.stencilFuncRef;
  1455. }
  1456. /**
  1457. * Gets the current stencil mask
  1458. * @returns a number defining the stencil mask to use
  1459. */
  1460. public getStencilFunctionMask(): number {
  1461. return this._stencilState.stencilFuncMask;
  1462. }
  1463. /**
  1464. * Sets the current stencil function
  1465. * @param stencilFunc defines the new stencil function to use
  1466. */
  1467. public setStencilFunction(stencilFunc: number) {
  1468. this._stencilState.stencilFunc = stencilFunc;
  1469. }
  1470. /**
  1471. * Sets the current stencil reference
  1472. * @param reference defines the new stencil reference to use
  1473. */
  1474. public setStencilFunctionReference(reference: number) {
  1475. this._stencilState.stencilFuncRef = reference;
  1476. }
  1477. /**
  1478. * Sets the current stencil mask
  1479. * @param mask defines the new stencil mask to use
  1480. */
  1481. public setStencilFunctionMask(mask: number) {
  1482. this._stencilState.stencilFuncMask = mask;
  1483. }
  1484. /**
  1485. * Gets the current stencil operation when stencil fails
  1486. * @returns a number defining stencil operation to use when stencil fails
  1487. */
  1488. public getStencilOperationFail(): number {
  1489. return this._stencilState.stencilOpStencilFail;
  1490. }
  1491. /**
  1492. * Gets the current stencil operation when depth fails
  1493. * @returns a number defining stencil operation to use when depth fails
  1494. */
  1495. public getStencilOperationDepthFail(): number {
  1496. return this._stencilState.stencilOpDepthFail;
  1497. }
  1498. /**
  1499. * Gets the current stencil operation when stencil passes
  1500. * @returns a number defining stencil operation to use when stencil passes
  1501. */
  1502. public getStencilOperationPass(): number {
  1503. return this._stencilState.stencilOpStencilDepthPass;
  1504. }
  1505. /**
  1506. * Sets the stencil operation to use when stencil fails
  1507. * @param operation defines the stencil operation to use when stencil fails
  1508. */
  1509. public setStencilOperationFail(operation: number): void {
  1510. this._stencilState.stencilOpStencilFail = operation;
  1511. }
  1512. /**
  1513. * Sets the stencil operation to use when depth fails
  1514. * @param operation defines the stencil operation to use when depth fails
  1515. */
  1516. public setStencilOperationDepthFail(operation: number): void {
  1517. this._stencilState.stencilOpDepthFail = operation;
  1518. }
  1519. /**
  1520. * Sets the stencil operation to use when stencil passes
  1521. * @param operation defines the stencil operation to use when stencil passes
  1522. */
  1523. public setStencilOperationPass(operation: number): void {
  1524. this._stencilState.stencilOpStencilDepthPass = operation;
  1525. }
  1526. /**
  1527. * Sets a boolean indicating if the dithering state is enabled or disabled
  1528. * @param value defines the dithering state
  1529. */
  1530. public setDitheringState(value: boolean): void {
  1531. if (value) {
  1532. this._gl.enable(this._gl.DITHER);
  1533. } else {
  1534. this._gl.disable(this._gl.DITHER);
  1535. }
  1536. }
  1537. /**
  1538. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1539. * @param value defines the rasterizer state
  1540. */
  1541. public setRasterizerState(value: boolean): void {
  1542. if (value) {
  1543. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1544. } else {
  1545. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1546. }
  1547. }
  1548. /**
  1549. * stop executing a render loop function and remove it from the execution array
  1550. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1551. */
  1552. public stopRenderLoop(renderFunction?: () => void): void {
  1553. if (!renderFunction) {
  1554. this._activeRenderLoops = [];
  1555. return;
  1556. }
  1557. var index = this._activeRenderLoops.indexOf(renderFunction);
  1558. if (index >= 0) {
  1559. this._activeRenderLoops.splice(index, 1);
  1560. }
  1561. }
  1562. /** @hidden */
  1563. public _renderLoop(): void {
  1564. if (!this._contextWasLost) {
  1565. var shouldRender = true;
  1566. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1567. shouldRender = false;
  1568. }
  1569. if (shouldRender) {
  1570. // Start new frame
  1571. this.beginFrame();
  1572. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1573. var renderFunction = this._activeRenderLoops[index];
  1574. renderFunction();
  1575. }
  1576. // Present
  1577. this.endFrame();
  1578. }
  1579. }
  1580. if (this._activeRenderLoops.length > 0) {
  1581. // Register new frame
  1582. var requester = null;
  1583. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1584. requester = this._vrDisplay;
  1585. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1586. } else {
  1587. this._renderingQueueLaunched = false;
  1588. }
  1589. }
  1590. /**
  1591. * Register and execute a render loop. The engine can have more than one render function
  1592. * @param renderFunction defines the function to continuously execute
  1593. */
  1594. public runRenderLoop(renderFunction: () => void): void {
  1595. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1596. return;
  1597. }
  1598. this._activeRenderLoops.push(renderFunction);
  1599. if (!this._renderingQueueLaunched) {
  1600. this._renderingQueueLaunched = true;
  1601. this._bindedRenderFunction = this._renderLoop.bind(this);
  1602. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1603. }
  1604. }
  1605. /**
  1606. * Toggle full screen mode
  1607. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1608. * @param options defines an option object to be sent to the requestFullscreen function
  1609. */
  1610. public switchFullscreen(requestPointerLock: boolean): void {
  1611. if (this.isFullscreen) {
  1612. Tools.ExitFullscreen();
  1613. } else {
  1614. this._pointerLockRequested = requestPointerLock;
  1615. if (this._renderingCanvas) {
  1616. Tools.RequestFullscreen(this._renderingCanvas);
  1617. }
  1618. }
  1619. }
  1620. /**
  1621. * Clear the current render buffer or the current render target (if any is set up)
  1622. * @param color defines the color to use
  1623. * @param backBuffer defines if the back buffer must be cleared
  1624. * @param depth defines if the depth buffer must be cleared
  1625. * @param stencil defines if the stencil buffer must be cleared
  1626. */
  1627. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1628. this.applyStates();
  1629. var mode = 0;
  1630. if (backBuffer && color) {
  1631. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1632. mode |= this._gl.COLOR_BUFFER_BIT;
  1633. }
  1634. if (depth) {
  1635. this._gl.clearDepth(1.0);
  1636. mode |= this._gl.DEPTH_BUFFER_BIT;
  1637. }
  1638. if (stencil) {
  1639. this._gl.clearStencil(0);
  1640. mode |= this._gl.STENCIL_BUFFER_BIT;
  1641. }
  1642. this._gl.clear(mode);
  1643. }
  1644. /**
  1645. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1646. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1647. * @param y defines the y-coordinate of the corner of the clear rectangle
  1648. * @param width defines the width of the clear rectangle
  1649. * @param height defines the height of the clear rectangle
  1650. * @param clearColor defines the clear color
  1651. */
  1652. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1653. let gl = this._gl;
  1654. // Save state
  1655. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1656. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1657. // Change state
  1658. gl.enable(gl.SCISSOR_TEST);
  1659. gl.scissor(x, y, width, height);
  1660. // Clear
  1661. this.clear(clearColor, true, true, true);
  1662. // Restore state
  1663. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1664. if (curScissor === true) {
  1665. gl.enable(gl.SCISSOR_TEST);
  1666. } else {
  1667. gl.disable(gl.SCISSOR_TEST);
  1668. }
  1669. }
  1670. private _viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  1671. /** @hidden */
  1672. public _viewport(x: number, y: number, width: number, height: number): void {
  1673. if (x !== this._viewportCached.x ||
  1674. y !== this._viewportCached.y ||
  1675. width !== this._viewportCached.z ||
  1676. height !== this._viewportCached.w)
  1677. {
  1678. this._viewportCached.x = x;
  1679. this._viewportCached.y = y;
  1680. this._viewportCached.z = width;
  1681. this._viewportCached.w = height;
  1682. this._gl.viewport(x, y, width, height);
  1683. }
  1684. }
  1685. /**
  1686. * Set the WebGL's viewport
  1687. * @param viewport defines the viewport element to be used
  1688. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1689. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1690. */
  1691. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1692. var width = requiredWidth || this.getRenderWidth();
  1693. var height = requiredHeight || this.getRenderHeight();
  1694. var x = viewport.x || 0;
  1695. var y = viewport.y || 0;
  1696. this._cachedViewport = viewport;
  1697. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1698. }
  1699. /**
  1700. * Directly set the WebGL Viewport
  1701. * @param x defines the x coordinate of the viewport (in screen space)
  1702. * @param y defines the y coordinate of the viewport (in screen space)
  1703. * @param width defines the width of the viewport (in screen space)
  1704. * @param height defines the height of the viewport (in screen space)
  1705. * @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
  1706. */
  1707. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1708. let currentViewport = this._cachedViewport;
  1709. this._cachedViewport = null;
  1710. this._viewport(x, y, width, height);
  1711. return currentViewport;
  1712. }
  1713. /**
  1714. * Begin a new frame
  1715. */
  1716. public beginFrame(): void {
  1717. this.onBeginFrameObservable.notifyObservers(this);
  1718. this._measureFps();
  1719. }
  1720. /**
  1721. * Enf the current frame
  1722. */
  1723. public endFrame(): void {
  1724. // Force a flush in case we are using a bad OS.
  1725. if (this._badOS) {
  1726. this.flushFramebuffer();
  1727. }
  1728. // Submit frame to the vr device, if enabled
  1729. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1730. // TODO: We should only submit the frame if we read frameData successfully.
  1731. this._vrDisplay.submitFrame();
  1732. }
  1733. this.onEndFrameObservable.notifyObservers(this);
  1734. }
  1735. /**
  1736. * Resize the view according to the canvas' size
  1737. */
  1738. public resize(): void {
  1739. // We're not resizing the size of the canvas while in VR mode & presenting
  1740. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1741. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1742. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1743. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1744. }
  1745. }
  1746. /**
  1747. * Force a specific size of the canvas
  1748. * @param width defines the new canvas' width
  1749. * @param height defines the new canvas' height
  1750. */
  1751. public setSize(width: number, height: number): void {
  1752. if (!this._renderingCanvas) {
  1753. return;
  1754. }
  1755. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1756. return;
  1757. }
  1758. this._renderingCanvas.width = width;
  1759. this._renderingCanvas.height = height;
  1760. for (var index = 0; index < this.scenes.length; index++) {
  1761. var scene = this.scenes[index];
  1762. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1763. var cam = scene.cameras[camIndex];
  1764. cam._currentRenderId = 0;
  1765. }
  1766. }
  1767. if (this.onResizeObservable.hasObservers) {
  1768. this.onResizeObservable.notifyObservers(this);
  1769. }
  1770. }
  1771. // WebVR functions
  1772. /**
  1773. * Gets a boolean indicating if a webVR device was detected
  1774. * @returns true if a webVR device was detected
  1775. */
  1776. public isVRDevicePresent(): boolean {
  1777. return !!this._vrDisplay;
  1778. }
  1779. /**
  1780. * Gets the current webVR device
  1781. * @returns the current webVR device (or null)
  1782. */
  1783. public getVRDevice(): any {
  1784. return this._vrDisplay;
  1785. }
  1786. /**
  1787. * Initializes a webVR display and starts listening to display change events
  1788. * The onVRDisplayChangedObservable will be notified upon these changes
  1789. * @returns The onVRDisplayChangedObservable
  1790. */
  1791. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1792. this.initWebVRAsync();
  1793. return this.onVRDisplayChangedObservable;
  1794. }
  1795. /**
  1796. * Initializes a webVR display and starts listening to display change events
  1797. * The onVRDisplayChangedObservable will be notified upon these changes
  1798. * @returns A promise containing a VRDisplay and if vr is supported
  1799. */
  1800. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1801. var notifyObservers = () => {
  1802. var eventArgs = {
  1803. vrDisplay: this._vrDisplay,
  1804. vrSupported: this._vrSupported
  1805. };
  1806. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1807. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1808. }
  1809. if (!this._onVrDisplayConnect) {
  1810. this._onVrDisplayConnect = (event) => {
  1811. this._vrDisplay = event.display;
  1812. notifyObservers();
  1813. };
  1814. this._onVrDisplayDisconnect = () => {
  1815. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1816. this._vrDisplay = undefined;
  1817. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1818. notifyObservers();
  1819. };
  1820. this._onVrDisplayPresentChange = () => {
  1821. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1822. }
  1823. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1824. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1825. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1826. }
  1827. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1828. this._webVRInitPromise.then(notifyObservers);
  1829. return this._webVRInitPromise;
  1830. }
  1831. /**
  1832. * Call this function to switch to webVR mode
  1833. * Will do nothing if webVR is not supported or if there is no webVR device
  1834. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1835. */
  1836. public enableVR() {
  1837. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1838. var onResolved = () => {
  1839. this.onVRRequestPresentComplete.notifyObservers(true);
  1840. this._onVRFullScreenTriggered();
  1841. };
  1842. var onRejected = () => {
  1843. this.onVRRequestPresentComplete.notifyObservers(false);
  1844. };
  1845. this.onVRRequestPresentStart.notifyObservers(this);
  1846. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1847. }
  1848. }
  1849. /**
  1850. * Call this function to leave webVR mode
  1851. * Will do nothing if webVR is not supported or if there is no webVR device
  1852. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1853. */
  1854. public disableVR() {
  1855. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1856. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1857. }
  1858. }
  1859. private _onVRFullScreenTriggered = () => {
  1860. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1861. //get the old size before we change
  1862. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1863. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1864. //get the width and height, change the render size
  1865. var leftEye = this._vrDisplay.getEyeParameters('left');
  1866. this.setHardwareScalingLevel(1);
  1867. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1868. } else {
  1869. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1870. this.setSize(this._oldSize.width, this._oldSize.height);
  1871. }
  1872. }
  1873. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  1874. return new Promise((res, rej)=>{
  1875. if (navigator.getVRDisplays) {
  1876. navigator.getVRDisplays().then((devices: Array<any>)=>{
  1877. this._vrSupported = true;
  1878. // note that devices may actually be an empty array. This is fine;
  1879. // we expect this._vrDisplay to be undefined in this case.
  1880. this._vrDisplay = devices[0];
  1881. res({
  1882. vrDisplay: this._vrDisplay,
  1883. vrSupported: this._vrSupported
  1884. });
  1885. });
  1886. } else {
  1887. this._vrDisplay = undefined;
  1888. this._vrSupported = false;
  1889. res({
  1890. vrDisplay: this._vrDisplay,
  1891. vrSupported: this._vrSupported
  1892. });
  1893. }
  1894. });
  1895. }
  1896. /**
  1897. * Binds the frame buffer to the specified texture.
  1898. * @param texture The texture to render to or null for the default canvas
  1899. * @param faceIndex The face of the texture to render to in case of cube texture
  1900. * @param requiredWidth The width of the target to render to
  1901. * @param requiredHeight The height of the target to render to
  1902. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1903. * @param depthStencilTexture The depth stencil texture to use to render
  1904. * @param lodLevel defines le lod level to bind to the frame buffer
  1905. */
  1906. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  1907. if (this._currentRenderTarget) {
  1908. this.unBindFramebuffer(this._currentRenderTarget);
  1909. }
  1910. this._currentRenderTarget = texture;
  1911. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1912. var gl = this._gl;
  1913. if (texture.isCube) {
  1914. if (faceIndex === undefined) {
  1915. faceIndex = 0;
  1916. }
  1917. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1918. if (depthStencilTexture) {
  1919. if (depthStencilTexture._generateStencilBuffer) {
  1920. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1921. }
  1922. else {
  1923. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1924. }
  1925. }
  1926. }
  1927. if (this._cachedViewport && !forceFullscreenViewport) {
  1928. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1929. } else {
  1930. if (!requiredWidth) {
  1931. requiredWidth = texture.width;
  1932. if (lodLevel) {
  1933. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1934. }
  1935. }
  1936. if (!requiredHeight) {
  1937. requiredHeight = texture.height;
  1938. if (lodLevel) {
  1939. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1940. }
  1941. }
  1942. this._viewport(0, 0, requiredWidth, requiredHeight);
  1943. }
  1944. this.wipeCaches();
  1945. }
  1946. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1947. if (this._currentFramebuffer !== framebuffer) {
  1948. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1949. this._currentFramebuffer = framebuffer;
  1950. }
  1951. }
  1952. /**
  1953. * Unbind the current render target texture from the webGL context
  1954. * @param texture defines the render target texture to unbind
  1955. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1956. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1957. */
  1958. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1959. this._currentRenderTarget = null;
  1960. // If MSAA, we need to bitblt back to main texture
  1961. var gl = this._gl;
  1962. if (texture._MSAAFramebuffer) {
  1963. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1964. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1965. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1966. 0, 0, texture.width, texture.height,
  1967. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1968. }
  1969. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1970. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1971. gl.generateMipmap(gl.TEXTURE_2D);
  1972. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1973. }
  1974. if (onBeforeUnbind) {
  1975. if (texture._MSAAFramebuffer) {
  1976. // Bind the correct framebuffer
  1977. this.bindUnboundFramebuffer(texture._framebuffer);
  1978. }
  1979. onBeforeUnbind();
  1980. }
  1981. this.bindUnboundFramebuffer(null);
  1982. }
  1983. /**
  1984. * Unbind a list of render target textures from the webGL context
  1985. * This is used only when drawBuffer extension or webGL2 are active
  1986. * @param textures defines the render target textures to unbind
  1987. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1988. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1989. */
  1990. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1991. this._currentRenderTarget = null;
  1992. // If MSAA, we need to bitblt back to main texture
  1993. var gl = this._gl;
  1994. if (textures[0]._MSAAFramebuffer) {
  1995. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1996. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1997. var attachments = textures[0]._attachments;
  1998. if (!attachments) {
  1999. attachments = new Array(textures.length);
  2000. textures[0]._attachments = attachments;
  2001. }
  2002. for (var i = 0; i < textures.length; i++) {
  2003. var texture = textures[i];
  2004. for (var j = 0; j < attachments.length; j++) {
  2005. attachments[j] = gl.NONE;
  2006. }
  2007. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2008. gl.readBuffer(attachments[i]);
  2009. gl.drawBuffers(attachments);
  2010. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2011. 0, 0, texture.width, texture.height,
  2012. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2013. }
  2014. for (var i = 0; i < attachments.length; i++) {
  2015. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2016. }
  2017. gl.drawBuffers(attachments);
  2018. }
  2019. for (var i = 0; i < textures.length; i++) {
  2020. var texture = textures[i];
  2021. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2022. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2023. gl.generateMipmap(gl.TEXTURE_2D);
  2024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2025. }
  2026. }
  2027. if (onBeforeUnbind) {
  2028. if (textures[0]._MSAAFramebuffer) {
  2029. // Bind the correct framebuffer
  2030. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  2031. }
  2032. onBeforeUnbind();
  2033. }
  2034. this.bindUnboundFramebuffer(null);
  2035. }
  2036. /**
  2037. * Force the mipmap generation for the given render target texture
  2038. * @param texture defines the render target texture to use
  2039. */
  2040. public generateMipMapsForCubemap(texture: InternalTexture) {
  2041. if (texture.generateMipMaps) {
  2042. var gl = this._gl;
  2043. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2044. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2045. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2046. }
  2047. }
  2048. /**
  2049. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2050. */
  2051. public flushFramebuffer(): void {
  2052. this._gl.flush();
  2053. }
  2054. /**
  2055. * Unbind the current render target and bind the default framebuffer
  2056. */
  2057. public restoreDefaultFramebuffer(): void {
  2058. if (this._currentRenderTarget) {
  2059. this.unBindFramebuffer(this._currentRenderTarget);
  2060. } else {
  2061. this.bindUnboundFramebuffer(null);
  2062. }
  2063. if (this._cachedViewport) {
  2064. this.setViewport(this._cachedViewport);
  2065. }
  2066. this.wipeCaches();
  2067. }
  2068. // UBOs
  2069. /**
  2070. * Create an uniform buffer
  2071. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2072. * @param elements defines the content of the uniform buffer
  2073. * @returns the webGL uniform buffer
  2074. */
  2075. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2076. var ubo = this._gl.createBuffer();
  2077. if (!ubo) {
  2078. throw new Error("Unable to create uniform buffer");
  2079. }
  2080. this.bindUniformBuffer(ubo);
  2081. if (elements instanceof Float32Array) {
  2082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2083. } else {
  2084. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2085. }
  2086. this.bindUniformBuffer(null);
  2087. ubo.references = 1;
  2088. return ubo;
  2089. }
  2090. /**
  2091. * Create a dynamic uniform buffer
  2092. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2093. * @param elements defines the content of the uniform buffer
  2094. * @returns the webGL uniform buffer
  2095. */
  2096. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2097. var ubo = this._gl.createBuffer();
  2098. if (!ubo) {
  2099. throw new Error("Unable to create dynamic uniform buffer");
  2100. }
  2101. this.bindUniformBuffer(ubo);
  2102. if (elements instanceof Float32Array) {
  2103. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2104. } else {
  2105. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2106. }
  2107. this.bindUniformBuffer(null);
  2108. ubo.references = 1;
  2109. return ubo;
  2110. }
  2111. /**
  2112. * Update an existing uniform buffer
  2113. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2114. * @param uniformBuffer defines the target uniform buffer
  2115. * @param elements defines the content to update
  2116. * @param offset defines the offset in the uniform buffer where update should start
  2117. * @param count defines the size of the data to update
  2118. */
  2119. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2120. this.bindUniformBuffer(uniformBuffer);
  2121. if (offset === undefined) {
  2122. offset = 0;
  2123. }
  2124. if (count === undefined) {
  2125. if (elements instanceof Float32Array) {
  2126. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2127. } else {
  2128. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2129. }
  2130. } else {
  2131. if (elements instanceof Float32Array) {
  2132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2133. } else {
  2134. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2135. }
  2136. }
  2137. this.bindUniformBuffer(null);
  2138. }
  2139. // VBOs
  2140. private _resetVertexBufferBinding(): void {
  2141. this.bindArrayBuffer(null);
  2142. this._cachedVertexBuffers = null;
  2143. }
  2144. /**
  2145. * Creates a vertex buffer
  2146. * @param data the data for the vertex buffer
  2147. * @returns the new WebGL static buffer
  2148. */
  2149. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2150. var vbo = this._gl.createBuffer();
  2151. if (!vbo) {
  2152. throw new Error("Unable to create vertex buffer");
  2153. }
  2154. this.bindArrayBuffer(vbo);
  2155. if (data instanceof Array) {
  2156. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2157. } else {
  2158. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2159. }
  2160. this._resetVertexBufferBinding();
  2161. vbo.references = 1;
  2162. return vbo;
  2163. }
  2164. /**
  2165. * Creates a dynamic vertex buffer
  2166. * @param data the data for the dynamic vertex buffer
  2167. * @returns the new WebGL dynamic buffer
  2168. */
  2169. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2170. var vbo = this._gl.createBuffer();
  2171. if (!vbo) {
  2172. throw new Error("Unable to create dynamic vertex buffer");
  2173. }
  2174. this.bindArrayBuffer(vbo);
  2175. if (data instanceof Array) {
  2176. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2177. } else {
  2178. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2179. }
  2180. this._resetVertexBufferBinding();
  2181. vbo.references = 1;
  2182. return vbo;
  2183. }
  2184. /**
  2185. * Update a dynamic index buffer
  2186. * @param indexBuffer defines the target index buffer
  2187. * @param indices defines the data to update
  2188. * @param offset defines the offset in the target index buffer where update should start
  2189. */
  2190. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2191. // Force cache update
  2192. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2193. this.bindIndexBuffer(indexBuffer);
  2194. var arrayBuffer;
  2195. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2196. arrayBuffer = indices;
  2197. } else {
  2198. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2199. }
  2200. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2201. this._resetIndexBufferBinding();
  2202. }
  2203. /**
  2204. * Updates a dynamic vertex buffer.
  2205. * @param vertexBuffer the vertex buffer to update
  2206. * @param data the data used to update the vertex buffer
  2207. * @param byteOffset the byte offset of the data
  2208. * @param byteLength the byte length of the data
  2209. */
  2210. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2211. this.bindArrayBuffer(vertexBuffer);
  2212. if (byteOffset === undefined) {
  2213. byteOffset = 0;
  2214. }
  2215. if (byteLength === undefined) {
  2216. if (data instanceof Array) {
  2217. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2218. } else {
  2219. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2220. }
  2221. } else {
  2222. if (data instanceof Array) {
  2223. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2224. } else {
  2225. if (data instanceof ArrayBuffer) {
  2226. data = new Uint8Array(data, byteOffset, byteLength);
  2227. } else {
  2228. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2229. }
  2230. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2231. }
  2232. }
  2233. this._resetVertexBufferBinding();
  2234. }
  2235. private _resetIndexBufferBinding(): void {
  2236. this.bindIndexBuffer(null);
  2237. this._cachedIndexBuffer = null;
  2238. }
  2239. /**
  2240. * Creates a new index buffer
  2241. * @param indices defines the content of the index buffer
  2242. * @param updatable defines if the index buffer must be updatable
  2243. * @returns a new webGL buffer
  2244. */
  2245. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2246. var vbo = this._gl.createBuffer();
  2247. if (!vbo) {
  2248. throw new Error("Unable to create index buffer");
  2249. }
  2250. this.bindIndexBuffer(vbo);
  2251. // Check for 32 bits indices
  2252. var arrayBuffer;
  2253. var need32Bits = false;
  2254. if (indices instanceof Uint16Array) {
  2255. arrayBuffer = indices;
  2256. } else {
  2257. //check 32 bit support
  2258. if (this._caps.uintIndices) {
  2259. if (indices instanceof Uint32Array) {
  2260. arrayBuffer = indices;
  2261. need32Bits = true;
  2262. } else {
  2263. //number[] or Int32Array, check if 32 bit is necessary
  2264. for (var index = 0; index < indices.length; index++) {
  2265. if (indices[index] > 65535) {
  2266. need32Bits = true;
  2267. break;
  2268. }
  2269. }
  2270. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2271. }
  2272. } else {
  2273. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2274. arrayBuffer = new Uint16Array(indices);
  2275. }
  2276. }
  2277. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2278. this._resetIndexBufferBinding();
  2279. vbo.references = 1;
  2280. vbo.is32Bits = need32Bits;
  2281. return vbo;
  2282. }
  2283. /**
  2284. * Bind a webGL buffer to the webGL context
  2285. * @param buffer defines the buffer to bind
  2286. */
  2287. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2288. if (!this._vaoRecordInProgress) {
  2289. this._unbindVertexArrayObject();
  2290. }
  2291. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2292. }
  2293. /**
  2294. * Bind an uniform buffer to the current webGL context
  2295. * @param buffer defines the buffer to bind
  2296. */
  2297. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2298. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2299. }
  2300. /**
  2301. * Bind a buffer to the current webGL context at a given location
  2302. * @param buffer defines the buffer to bind
  2303. * @param location defines the index where to bind the buffer
  2304. */
  2305. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2306. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2307. }
  2308. /**
  2309. * Bind a specific block at a given index in a specific shader program
  2310. * @param shaderProgram defines the shader program
  2311. * @param blockName defines the block name
  2312. * @param index defines the index where to bind the block
  2313. */
  2314. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2315. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2316. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2317. };
  2318. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2319. if (!this._vaoRecordInProgress) {
  2320. this._unbindVertexArrayObject();
  2321. }
  2322. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2323. }
  2324. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2325. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2326. this._gl.bindBuffer(target, buffer);
  2327. this._currentBoundBuffer[target] = buffer;
  2328. }
  2329. }
  2330. /**
  2331. * update the bound buffer with the given data
  2332. * @param data defines the data to update
  2333. */
  2334. public updateArrayBuffer(data: Float32Array): void {
  2335. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2336. }
  2337. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2338. var pointer = this._currentBufferPointers[indx];
  2339. var changed = false;
  2340. if (!pointer.active) {
  2341. changed = true;
  2342. pointer.active = true;
  2343. pointer.index = indx;
  2344. pointer.size = size;
  2345. pointer.type = type;
  2346. pointer.normalized = normalized;
  2347. pointer.stride = stride;
  2348. pointer.offset = offset;
  2349. pointer.buffer = buffer;
  2350. } else {
  2351. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2352. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2353. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2354. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2355. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2356. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2357. }
  2358. if (changed || this._vaoRecordInProgress) {
  2359. this.bindArrayBuffer(buffer);
  2360. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2361. }
  2362. }
  2363. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2364. if (indexBuffer == null) {
  2365. return;
  2366. }
  2367. if (this._cachedIndexBuffer !== indexBuffer) {
  2368. this._cachedIndexBuffer = indexBuffer;
  2369. this.bindIndexBuffer(indexBuffer);
  2370. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2371. }
  2372. }
  2373. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2374. var attributes = effect.getAttributesNames();
  2375. if (!this._vaoRecordInProgress) {
  2376. this._unbindVertexArrayObject();
  2377. }
  2378. this.unbindAllAttributes();
  2379. for (var index = 0; index < attributes.length; index++) {
  2380. var order = effect.getAttributeLocation(index);
  2381. if (order >= 0) {
  2382. var vertexBuffer = vertexBuffers[attributes[index]];
  2383. if (!vertexBuffer) {
  2384. continue;
  2385. }
  2386. this._gl.enableVertexAttribArray(order);
  2387. if (!this._vaoRecordInProgress) {
  2388. this._vertexAttribArraysEnabled[order] = true;
  2389. }
  2390. var buffer = vertexBuffer.getBuffer();
  2391. if (buffer) {
  2392. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2393. if (vertexBuffer.getIsInstanced()) {
  2394. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2395. if (!this._vaoRecordInProgress) {
  2396. this._currentInstanceLocations.push(order);
  2397. this._currentInstanceBuffers.push(buffer);
  2398. }
  2399. }
  2400. }
  2401. }
  2402. }
  2403. }
  2404. /**
  2405. * Records a vertex array object
  2406. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2407. * @param vertexBuffers defines the list of vertex buffers to store
  2408. * @param indexBuffer defines the index buffer to store
  2409. * @param effect defines the effect to store
  2410. * @returns the new vertex array object
  2411. */
  2412. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2413. var vao = this._gl.createVertexArray();
  2414. this._vaoRecordInProgress = true;
  2415. this._gl.bindVertexArray(vao);
  2416. this._mustWipeVertexAttributes = true;
  2417. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2418. this.bindIndexBuffer(indexBuffer);
  2419. this._vaoRecordInProgress = false;
  2420. this._gl.bindVertexArray(null);
  2421. return vao;
  2422. }
  2423. /**
  2424. * Bind a specific vertex array object
  2425. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2426. * @param vertexArrayObject defines the vertex array object to bind
  2427. * @param indexBuffer defines the index buffer to bind
  2428. */
  2429. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2430. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2431. this._cachedVertexArrayObject = vertexArrayObject;
  2432. this._gl.bindVertexArray(vertexArrayObject);
  2433. this._cachedVertexBuffers = null;
  2434. this._cachedIndexBuffer = null;
  2435. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2436. this._mustWipeVertexAttributes = true;
  2437. }
  2438. }
  2439. /**
  2440. * Bind webGl buffers directly to the webGL context
  2441. * @param vertexBuffer defines the vertex buffer to bind
  2442. * @param indexBuffer defines the index buffer to bind
  2443. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2444. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2445. * @param effect defines the effect associated with the vertex buffer
  2446. */
  2447. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2448. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2449. this._cachedVertexBuffers = vertexBuffer;
  2450. this._cachedEffectForVertexBuffers = effect;
  2451. let attributesCount = effect.getAttributesCount();
  2452. this._unbindVertexArrayObject();
  2453. this.unbindAllAttributes();
  2454. var offset = 0;
  2455. for (var index = 0; index < attributesCount; index++) {
  2456. if (index < vertexDeclaration.length) {
  2457. var order = effect.getAttributeLocation(index);
  2458. if (order >= 0) {
  2459. this._gl.enableVertexAttribArray(order);
  2460. this._vertexAttribArraysEnabled[order] = true;
  2461. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2462. }
  2463. offset += vertexDeclaration[index] * 4;
  2464. }
  2465. }
  2466. }
  2467. this._bindIndexBufferWithCache(indexBuffer);
  2468. }
  2469. private _unbindVertexArrayObject(): void {
  2470. if (!this._cachedVertexArrayObject) {
  2471. return;
  2472. }
  2473. this._cachedVertexArrayObject = null;
  2474. this._gl.bindVertexArray(null);
  2475. }
  2476. /**
  2477. * Bind a list of vertex buffers to the webGL context
  2478. * @param vertexBuffers defines the list of vertex buffers to bind
  2479. * @param indexBuffer defines the index buffer to bind
  2480. * @param effect defines the effect associated with the vertex buffers
  2481. */
  2482. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2483. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2484. this._cachedVertexBuffers = vertexBuffers;
  2485. this._cachedEffectForVertexBuffers = effect;
  2486. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2487. }
  2488. this._bindIndexBufferWithCache(indexBuffer);
  2489. }
  2490. /**
  2491. * Unbind all instance attributes
  2492. */
  2493. public unbindInstanceAttributes() {
  2494. var boundBuffer;
  2495. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2496. var instancesBuffer = this._currentInstanceBuffers[i];
  2497. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2498. boundBuffer = instancesBuffer;
  2499. this.bindArrayBuffer(instancesBuffer);
  2500. }
  2501. var offsetLocation = this._currentInstanceLocations[i];
  2502. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2503. }
  2504. this._currentInstanceBuffers.length = 0;
  2505. this._currentInstanceLocations.length = 0;
  2506. }
  2507. /**
  2508. * Release and free the memory of a vertex array object
  2509. * @param vao defines the vertex array object to delete
  2510. */
  2511. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2512. this._gl.deleteVertexArray(vao);
  2513. }
  2514. /** @hidden */
  2515. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2516. buffer.references--;
  2517. if (buffer.references === 0) {
  2518. this._gl.deleteBuffer(buffer);
  2519. return true;
  2520. }
  2521. return false;
  2522. }
  2523. /**
  2524. * Creates a webGL buffer to use with instanciation
  2525. * @param capacity defines the size of the buffer
  2526. * @returns the webGL buffer
  2527. */
  2528. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2529. var buffer = this._gl.createBuffer();
  2530. if (!buffer) {
  2531. throw new Error("Unable to create instance buffer");
  2532. }
  2533. buffer.capacity = capacity;
  2534. this.bindArrayBuffer(buffer);
  2535. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2536. return buffer;
  2537. }
  2538. /**
  2539. * Delete a webGL buffer used with instanciation
  2540. * @param buffer defines the webGL buffer to delete
  2541. */
  2542. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2543. this._gl.deleteBuffer(buffer);
  2544. }
  2545. /**
  2546. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2547. * @param instancesBuffer defines the webGL buffer to update and bind
  2548. * @param data defines the data to store in the buffer
  2549. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2550. */
  2551. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2552. this.bindArrayBuffer(instancesBuffer);
  2553. if (data) {
  2554. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2555. }
  2556. if ((<any>offsetLocations[0]).index !== undefined) {
  2557. let stride = 0;
  2558. for (let i = 0; i < offsetLocations.length; i++) {
  2559. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2560. stride += ai.attributeSize * 4;
  2561. }
  2562. for (let i = 0; i < offsetLocations.length; i++) {
  2563. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2564. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2565. this._gl.enableVertexAttribArray(ai.index);
  2566. this._vertexAttribArraysEnabled[ai.index] = true;
  2567. }
  2568. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2569. this._gl.vertexAttribDivisor(ai.index, 1);
  2570. this._currentInstanceLocations.push(ai.index);
  2571. this._currentInstanceBuffers.push(instancesBuffer);
  2572. }
  2573. } else {
  2574. for (let index = 0; index < 4; index++) {
  2575. let offsetLocation = <number>offsetLocations[index];
  2576. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2577. this._gl.enableVertexAttribArray(offsetLocation);
  2578. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2579. }
  2580. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2581. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2582. this._currentInstanceLocations.push(offsetLocation);
  2583. this._currentInstanceBuffers.push(instancesBuffer);
  2584. }
  2585. }
  2586. }
  2587. /**
  2588. * Apply all cached states (depth, culling, stencil and alpha)
  2589. */
  2590. public applyStates() {
  2591. this._depthCullingState.apply(this._gl);
  2592. this._stencilState.apply(this._gl);
  2593. this._alphaState.apply(this._gl);
  2594. }
  2595. /**
  2596. * Send a draw order
  2597. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2598. * @param indexStart defines the starting index
  2599. * @param indexCount defines the number of index to draw
  2600. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2601. */
  2602. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2603. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2604. }
  2605. /**
  2606. * Draw a list of points
  2607. * @param verticesStart defines the index of first vertex to draw
  2608. * @param verticesCount defines the count of vertices to draw
  2609. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2610. */
  2611. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2612. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2613. }
  2614. /**
  2615. * Draw a list of unindexed primitives
  2616. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2617. * @param verticesStart defines the index of first vertex to draw
  2618. * @param verticesCount defines the count of vertices to draw
  2619. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2620. */
  2621. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2622. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2623. }
  2624. /**
  2625. * Draw a list of indexed primitives
  2626. * @param fillMode defines the primitive to use
  2627. * @param indexStart defines the starting index
  2628. * @param indexCount defines the number of index to draw
  2629. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2630. */
  2631. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2632. // Apply states
  2633. this.applyStates();
  2634. this._drawCalls.addCount(1, false);
  2635. // Render
  2636. const drawMode = this._drawMode(fillMode);
  2637. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2638. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2639. if (instancesCount) {
  2640. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2641. } else {
  2642. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2643. }
  2644. }
  2645. /**
  2646. * Draw a list of unindexed primitives
  2647. * @param fillMode defines the primitive to use
  2648. * @param verticesStart defines the index of first vertex to draw
  2649. * @param verticesCount defines the count of vertices to draw
  2650. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2651. */
  2652. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2653. // Apply states
  2654. this.applyStates();
  2655. this._drawCalls.addCount(1, false);
  2656. const drawMode = this._drawMode(fillMode);
  2657. if (instancesCount) {
  2658. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2659. } else {
  2660. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2661. }
  2662. }
  2663. private _drawMode(fillMode: number): number {
  2664. switch (fillMode) {
  2665. // Triangle views
  2666. case Material.TriangleFillMode:
  2667. return this._gl.TRIANGLES;
  2668. case Material.PointFillMode:
  2669. return this._gl.POINTS;
  2670. case Material.WireFrameFillMode:
  2671. return this._gl.LINES;
  2672. // Draw modes
  2673. case Material.PointListDrawMode:
  2674. return this._gl.POINTS
  2675. case Material.LineListDrawMode:
  2676. return this._gl.LINES;
  2677. case Material.LineLoopDrawMode:
  2678. return this._gl.LINE_LOOP
  2679. case Material.LineStripDrawMode:
  2680. return this._gl.LINE_STRIP
  2681. case Material.TriangleStripDrawMode:
  2682. return this._gl.TRIANGLE_STRIP
  2683. case Material.TriangleFanDrawMode:
  2684. return this._gl.TRIANGLE_FAN;
  2685. default:
  2686. return this._gl.TRIANGLES;
  2687. }
  2688. }
  2689. // Shaders
  2690. /** @hidden */
  2691. public _releaseEffect(effect: Effect): void {
  2692. if (this._compiledEffects[effect._key]) {
  2693. delete this._compiledEffects[effect._key];
  2694. this._deleteProgram(effect.getProgram());
  2695. }
  2696. }
  2697. /** @hidden */
  2698. public _deleteProgram(program: WebGLProgram): void {
  2699. if (program) {
  2700. program.__SPECTOR_rebuildProgram = null;
  2701. if (program.transformFeedback) {
  2702. this.deleteTransformFeedback(program.transformFeedback);
  2703. program.transformFeedback = null;
  2704. }
  2705. this._gl.deleteProgram(program);
  2706. }
  2707. }
  2708. /**
  2709. * Create a new effect (used to store vertex/fragment shaders)
  2710. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2711. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2712. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2713. * @param samplers defines an array of string used to represent textures
  2714. * @param defines defines the string containing the defines to use to compile the shaders
  2715. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2716. * @param onCompiled defines a function to call when the effect creation is successful
  2717. * @param onError defines a function to call when the effect creation has failed
  2718. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2719. * @returns the new Effect
  2720. */
  2721. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2722. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2723. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2724. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2725. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2726. if (this._compiledEffects[name]) {
  2727. var compiledEffect = <Effect>this._compiledEffects[name];
  2728. if (onCompiled && compiledEffect.isReady()) {
  2729. onCompiled(compiledEffect);
  2730. }
  2731. return compiledEffect;
  2732. }
  2733. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2734. effect._key = name;
  2735. this._compiledEffects[name] = effect;
  2736. return effect;
  2737. }
  2738. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  2739. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  2740. };
  2741. private _compileRawShader(source: string, type: string): WebGLShader {
  2742. var gl = this._gl;
  2743. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2744. gl.shaderSource(shader, source);
  2745. gl.compileShader(shader);
  2746. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2747. let log = gl.getShaderInfoLog(shader);
  2748. if (log) {
  2749. throw new Error(log);
  2750. }
  2751. }
  2752. if (!shader) {
  2753. throw new Error("Something went wrong while compile the shader.");
  2754. }
  2755. return shader;
  2756. };
  2757. /**
  2758. * Directly creates a webGL program
  2759. * @param vertexCode defines the vertex shader code to use
  2760. * @param fragmentCode defines the fragment shader code to use
  2761. * @param context defines the webGL context to use (if not set, the current one will be used)
  2762. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2763. * @returns the new webGL program
  2764. */
  2765. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2766. context = context || this._gl;
  2767. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  2768. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  2769. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2770. }
  2771. /**
  2772. * Creates a webGL program
  2773. * @param vertexCode defines the vertex shader code to use
  2774. * @param fragmentCode defines the fragment shader code to use
  2775. * @param defines defines the string containing the defines to use to compile the shaders
  2776. * @param context defines the webGL context to use (if not set, the current one will be used)
  2777. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2778. * @returns the new webGL program
  2779. */
  2780. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2781. context = context || this._gl;
  2782. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2783. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2784. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  2785. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  2786. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2787. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2788. return program;
  2789. }
  2790. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2791. var shaderProgram = context.createProgram();
  2792. if (!shaderProgram) {
  2793. throw new Error("Unable to create program");
  2794. }
  2795. context.attachShader(shaderProgram, vertexShader);
  2796. context.attachShader(shaderProgram, fragmentShader);
  2797. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2798. let transformFeedback = this.createTransformFeedback();
  2799. this.bindTransformFeedback(transformFeedback);
  2800. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2801. shaderProgram.transformFeedback = transformFeedback;
  2802. }
  2803. context.linkProgram(shaderProgram);
  2804. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2805. this.bindTransformFeedback(null);
  2806. }
  2807. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2808. if (!linked) {
  2809. var error = context.getProgramInfoLog(shaderProgram);
  2810. if (error) {
  2811. throw new Error(error);
  2812. }
  2813. }
  2814. if (this.validateShaderPrograms) {
  2815. context.validateProgram(shaderProgram);
  2816. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  2817. if(!validated) {
  2818. var error = context.getProgramInfoLog(shaderProgram);
  2819. if (error) {
  2820. throw new Error(error);
  2821. }
  2822. }
  2823. }
  2824. context.deleteShader(vertexShader);
  2825. context.deleteShader(fragmentShader);
  2826. return shaderProgram;
  2827. }
  2828. /**
  2829. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2830. * @param shaderProgram defines the webGL program to use
  2831. * @param uniformsNames defines the list of uniform names
  2832. * @returns an array of webGL uniform locations
  2833. */
  2834. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2835. var results = new Array<Nullable<WebGLUniformLocation>>();
  2836. for (var index = 0; index < uniformsNames.length; index++) {
  2837. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2838. }
  2839. return results;
  2840. }
  2841. /**
  2842. * Gets the lsit of active attributes for a given webGL program
  2843. * @param shaderProgram defines the webGL program to use
  2844. * @param attributesNames defines the list of attribute names to get
  2845. * @returns an array of indices indicating the offset of each attribute
  2846. */
  2847. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2848. var results = [];
  2849. for (var index = 0; index < attributesNames.length; index++) {
  2850. try {
  2851. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2852. } catch (e) {
  2853. results.push(-1);
  2854. }
  2855. }
  2856. return results;
  2857. }
  2858. /**
  2859. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2860. * @param effect defines the effect to activate
  2861. */
  2862. public enableEffect(effect: Nullable<Effect>): void {
  2863. if (!effect || effect === this._currentEffect) {
  2864. return;
  2865. }
  2866. // Use program
  2867. this.bindSamplers(effect);
  2868. this._currentEffect = effect;
  2869. if (effect.onBind) {
  2870. effect.onBind(effect);
  2871. }
  2872. if (effect._onBindObservable) {
  2873. effect._onBindObservable.notifyObservers(effect);
  2874. }
  2875. }
  2876. /**
  2877. * Set the value of an uniform to an array of int32
  2878. * @param uniform defines the webGL uniform location where to store the value
  2879. * @param array defines the array of int32 to store
  2880. */
  2881. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2882. if (!uniform)
  2883. return;
  2884. this._gl.uniform1iv(uniform, array);
  2885. }
  2886. /**
  2887. * Set the value of an uniform to an array of int32 (stored as vec2)
  2888. * @param uniform defines the webGL uniform location where to store the value
  2889. * @param array defines the array of int32 to store
  2890. */
  2891. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2892. if (!uniform || array.length % 2 !== 0)
  2893. return;
  2894. this._gl.uniform2iv(uniform, array);
  2895. }
  2896. /**
  2897. * Set the value of an uniform to an array of int32 (stored as vec3)
  2898. * @param uniform defines the webGL uniform location where to store the value
  2899. * @param array defines the array of int32 to store
  2900. */
  2901. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2902. if (!uniform || array.length % 3 !== 0)
  2903. return;
  2904. this._gl.uniform3iv(uniform, array);
  2905. }
  2906. /**
  2907. * Set the value of an uniform to an array of int32 (stored as vec4)
  2908. * @param uniform defines the webGL uniform location where to store the value
  2909. * @param array defines the array of int32 to store
  2910. */
  2911. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2912. if (!uniform || array.length % 4 !== 0)
  2913. return;
  2914. this._gl.uniform4iv(uniform, array);
  2915. }
  2916. /**
  2917. * Set the value of an uniform to an array of float32
  2918. * @param uniform defines the webGL uniform location where to store the value
  2919. * @param array defines the array of float32 to store
  2920. */
  2921. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2922. if (!uniform)
  2923. return;
  2924. this._gl.uniform1fv(uniform, array);
  2925. }
  2926. /**
  2927. * Set the value of an uniform to an array of float32 (stored as vec2)
  2928. * @param uniform defines the webGL uniform location where to store the value
  2929. * @param array defines the array of float32 to store
  2930. */
  2931. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2932. if (!uniform || array.length % 2 !== 0)
  2933. return;
  2934. this._gl.uniform2fv(uniform, array);
  2935. }
  2936. /**
  2937. * Set the value of an uniform to an array of float32 (stored as vec3)
  2938. * @param uniform defines the webGL uniform location where to store the value
  2939. * @param array defines the array of float32 to store
  2940. */
  2941. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2942. if (!uniform || array.length % 3 !== 0)
  2943. return;
  2944. this._gl.uniform3fv(uniform, array);
  2945. }
  2946. /**
  2947. * Set the value of an uniform to an array of float32 (stored as vec4)
  2948. * @param uniform defines the webGL uniform location where to store the value
  2949. * @param array defines the array of float32 to store
  2950. */
  2951. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2952. if (!uniform || array.length % 4 !== 0)
  2953. return;
  2954. this._gl.uniform4fv(uniform, array);
  2955. }
  2956. /**
  2957. * Set the value of an uniform to an array of number
  2958. * @param uniform defines the webGL uniform location where to store the value
  2959. * @param array defines the array of number to store
  2960. */
  2961. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2962. if (!uniform)
  2963. return;
  2964. this._gl.uniform1fv(uniform, <any>array);
  2965. }
  2966. /**
  2967. * Set the value of an uniform to an array of number (stored as vec2)
  2968. * @param uniform defines the webGL uniform location where to store the value
  2969. * @param array defines the array of number to store
  2970. */
  2971. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2972. if (!uniform || array.length % 2 !== 0)
  2973. return;
  2974. this._gl.uniform2fv(uniform, <any>array);
  2975. }
  2976. /**
  2977. * Set the value of an uniform to an array of number (stored as vec3)
  2978. * @param uniform defines the webGL uniform location where to store the value
  2979. * @param array defines the array of number to store
  2980. */
  2981. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2982. if (!uniform || array.length % 3 !== 0)
  2983. return;
  2984. this._gl.uniform3fv(uniform, <any>array);
  2985. }
  2986. /**
  2987. * Set the value of an uniform to an array of number (stored as vec4)
  2988. * @param uniform defines the webGL uniform location where to store the value
  2989. * @param array defines the array of number to store
  2990. */
  2991. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2992. if (!uniform || array.length % 4 !== 0)
  2993. return;
  2994. this._gl.uniform4fv(uniform, <any>array);
  2995. }
  2996. /**
  2997. * Set the value of an uniform to an array of float32 (stored as matrices)
  2998. * @param uniform defines the webGL uniform location where to store the value
  2999. * @param matrices defines the array of float32 to store
  3000. */
  3001. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  3002. if (!uniform)
  3003. return;
  3004. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3005. }
  3006. /**
  3007. * Set the value of an uniform to a matrix
  3008. * @param uniform defines the webGL uniform location where to store the value
  3009. * @param matrix defines the matrix to store
  3010. */
  3011. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  3012. if (!uniform)
  3013. return;
  3014. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3015. }
  3016. /**
  3017. * Set the value of an uniform to a matrix (3x3)
  3018. * @param uniform defines the webGL uniform location where to store the value
  3019. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  3020. */
  3021. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3022. if (!uniform)
  3023. return;
  3024. this._gl.uniformMatrix3fv(uniform, false, matrix);
  3025. }
  3026. /**
  3027. * Set the value of an uniform to a matrix (2x2)
  3028. * @param uniform defines the webGL uniform location where to store the value
  3029. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  3030. */
  3031. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3032. if (!uniform)
  3033. return;
  3034. this._gl.uniformMatrix2fv(uniform, false, matrix);
  3035. }
  3036. /**
  3037. * Set the value of an uniform to a number (int)
  3038. * @param uniform defines the webGL uniform location where to store the value
  3039. * @param value defines the int number to store
  3040. */
  3041. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3042. if (!uniform)
  3043. return;
  3044. this._gl.uniform1i(uniform, value);
  3045. }
  3046. /**
  3047. * Set the value of an uniform to a number (float)
  3048. * @param uniform defines the webGL uniform location where to store the value
  3049. * @param value defines the float number to store
  3050. */
  3051. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3052. if (!uniform)
  3053. return;
  3054. this._gl.uniform1f(uniform, value);
  3055. }
  3056. /**
  3057. * Set the value of an uniform to a vec2
  3058. * @param uniform defines the webGL uniform location where to store the value
  3059. * @param x defines the 1st component of the value
  3060. * @param y defines the 2nd component of the value
  3061. */
  3062. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3063. if (!uniform)
  3064. return;
  3065. this._gl.uniform2f(uniform, x, y);
  3066. }
  3067. /**
  3068. * Set the value of an uniform to a vec3
  3069. * @param uniform defines the webGL uniform location where to store the value
  3070. * @param x defines the 1st component of the value
  3071. * @param y defines the 2nd component of the value
  3072. * @param z defines the 3rd component of the value
  3073. */
  3074. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3075. if (!uniform)
  3076. return;
  3077. this._gl.uniform3f(uniform, x, y, z);
  3078. }
  3079. /**
  3080. * Set the value of an uniform to a boolean
  3081. * @param uniform defines the webGL uniform location where to store the value
  3082. * @param bool defines the boolean to store
  3083. */
  3084. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3085. if (!uniform)
  3086. return;
  3087. this._gl.uniform1i(uniform, bool);
  3088. }
  3089. /**
  3090. * Set the value of an uniform to a vec4
  3091. * @param uniform defines the webGL uniform location where to store the value
  3092. * @param x defines the 1st component of the value
  3093. * @param y defines the 2nd component of the value
  3094. * @param z defines the 3rd component of the value
  3095. * @param w defines the 4th component of the value
  3096. */
  3097. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3098. if (!uniform)
  3099. return;
  3100. this._gl.uniform4f(uniform, x, y, z, w);
  3101. }
  3102. /**
  3103. * Set the value of an uniform to a Color3
  3104. * @param uniform defines the webGL uniform location where to store the value
  3105. * @param color3 defines the color to store
  3106. */
  3107. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3108. if (!uniform)
  3109. return;
  3110. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3111. }
  3112. /**
  3113. * Set the value of an uniform to a Color3 and an alpha value
  3114. * @param uniform defines the webGL uniform location where to store the value
  3115. * @param color3 defines the color to store
  3116. * @param alpha defines the alpha component to store
  3117. */
  3118. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3119. if (!uniform)
  3120. return;
  3121. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3122. }
  3123. /**
  3124. * Sets a Color4 on a uniform variable
  3125. * @param uniform defines the uniform location
  3126. * @param color4 defines the value to be set
  3127. */
  3128. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3129. if (!uniform)
  3130. return;
  3131. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3132. }
  3133. // States
  3134. /**
  3135. * Set various states to the webGL context
  3136. * @param culling defines backface culling state
  3137. * @param zOffset defines the value to apply to zOffset (0 by default)
  3138. * @param force defines if states must be applied even if cache is up to date
  3139. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3140. */
  3141. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3142. // Culling
  3143. if (this._depthCullingState.cull !== culling || force) {
  3144. this._depthCullingState.cull = culling;
  3145. }
  3146. // Cull face
  3147. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3148. if (this._depthCullingState.cullFace !== cullFace || force) {
  3149. this._depthCullingState.cullFace = cullFace;
  3150. }
  3151. // Z offset
  3152. this.setZOffset(zOffset);
  3153. // Front face
  3154. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3155. if (this._depthCullingState.frontFace !== frontFace || force) {
  3156. this._depthCullingState.frontFace = frontFace;
  3157. }
  3158. }
  3159. /**
  3160. * Set the z offset to apply to current rendering
  3161. * @param value defines the offset to apply
  3162. */
  3163. public setZOffset(value: number): void {
  3164. this._depthCullingState.zOffset = value;
  3165. }
  3166. /**
  3167. * Gets the current value of the zOffset
  3168. * @returns the current zOffset state
  3169. */
  3170. public getZOffset(): number {
  3171. return this._depthCullingState.zOffset;
  3172. }
  3173. /**
  3174. * Enable or disable depth buffering
  3175. * @param enable defines the state to set
  3176. */
  3177. public setDepthBuffer(enable: boolean): void {
  3178. this._depthCullingState.depthTest = enable;
  3179. }
  3180. /**
  3181. * Gets a boolean indicating if depth writing is enabled
  3182. * @returns the current depth writing state
  3183. */
  3184. public getDepthWrite(): boolean {
  3185. return this._depthCullingState.depthMask;
  3186. }
  3187. /**
  3188. * Enable or disable depth writing
  3189. * @param enable defines the state to set
  3190. */
  3191. public setDepthWrite(enable: boolean): void {
  3192. this._depthCullingState.depthMask = enable;
  3193. }
  3194. /**
  3195. * Enable or disable color writing
  3196. * @param enable defines the state to set
  3197. */
  3198. public setColorWrite(enable: boolean): void {
  3199. this._gl.colorMask(enable, enable, enable, enable);
  3200. this._colorWrite = enable;
  3201. }
  3202. /**
  3203. * Gets a boolean indicating if color writing is enabled
  3204. * @returns the current color writing state
  3205. */
  3206. public getColorWrite(): boolean {
  3207. return this._colorWrite;
  3208. }
  3209. /**
  3210. * Sets alpha constants used by some alpha blending modes
  3211. * @param r defines the red component
  3212. * @param g defines the green component
  3213. * @param b defines the blue component
  3214. * @param a defines the alpha component
  3215. */
  3216. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3217. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3218. }
  3219. /**
  3220. * Sets the current alpha mode
  3221. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  3222. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3223. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3224. */
  3225. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3226. if (this._alphaMode === mode) {
  3227. return;
  3228. }
  3229. switch (mode) {
  3230. case Engine.ALPHA_DISABLE:
  3231. this._alphaState.alphaBlend = false;
  3232. break;
  3233. case Engine.ALPHA_PREMULTIPLIED:
  3234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3235. this._alphaState.alphaBlend = true;
  3236. break;
  3237. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3239. this._alphaState.alphaBlend = true;
  3240. break;
  3241. case Engine.ALPHA_COMBINE:
  3242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3243. this._alphaState.alphaBlend = true;
  3244. break;
  3245. case Engine.ALPHA_ONEONE:
  3246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3247. this._alphaState.alphaBlend = true;
  3248. break;
  3249. case Engine.ALPHA_ADD:
  3250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3251. this._alphaState.alphaBlend = true;
  3252. break;
  3253. case Engine.ALPHA_SUBTRACT:
  3254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3255. this._alphaState.alphaBlend = true;
  3256. break;
  3257. case Engine.ALPHA_MULTIPLY:
  3258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3259. this._alphaState.alphaBlend = true;
  3260. break;
  3261. case Engine.ALPHA_MAXIMIZED:
  3262. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3263. this._alphaState.alphaBlend = true;
  3264. break;
  3265. case Engine.ALPHA_INTERPOLATE:
  3266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3267. this._alphaState.alphaBlend = true;
  3268. break;
  3269. case Engine.ALPHA_SCREENMODE:
  3270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3271. this._alphaState.alphaBlend = true;
  3272. break;
  3273. }
  3274. if (!noDepthWriteChange) {
  3275. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3276. }
  3277. this._alphaMode = mode;
  3278. }
  3279. /**
  3280. * Gets the current alpha mode
  3281. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3282. * @returns the current alpha mode
  3283. */
  3284. public getAlphaMode(): number {
  3285. return this._alphaMode;
  3286. }
  3287. // Textures
  3288. /**
  3289. * Clears the list of texture accessible through engine.
  3290. * This can help preventing texture load conflict due to name collision.
  3291. */
  3292. public clearInternalTexturesCache() {
  3293. this._internalTexturesCache = [];
  3294. }
  3295. /**
  3296. * Force the entire cache to be cleared
  3297. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3298. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3299. */
  3300. public wipeCaches(bruteForce?: boolean): void {
  3301. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3302. return;
  3303. }
  3304. this._currentEffect = null;
  3305. this._unpackFlipYCached = null;
  3306. this._viewportCached.x = 0;
  3307. this._viewportCached.y = 0;
  3308. this._viewportCached.z = 0;
  3309. this._viewportCached.w = 0;
  3310. if (bruteForce) {
  3311. this.resetTextureCache();
  3312. this._currentProgram = null;
  3313. this._stencilState.reset();
  3314. this._depthCullingState.reset();
  3315. this.setDepthFunctionToLessOrEqual();
  3316. this._alphaState.reset();
  3317. }
  3318. this._resetVertexBufferBinding();
  3319. this._cachedIndexBuffer = null;
  3320. this._cachedEffectForVertexBuffers = null;
  3321. this._unbindVertexArrayObject();
  3322. this.bindIndexBuffer(null);
  3323. }
  3324. /**
  3325. * Set the compressed texture format to use, based on the formats you have, and the formats
  3326. * supported by the hardware / browser.
  3327. *
  3328. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3329. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3330. * to API arguments needed to compressed textures. This puts the burden on the container
  3331. * generator to house the arcane code for determining these for current & future formats.
  3332. *
  3333. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3334. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3335. *
  3336. * Note: The result of this call is not taken into account when a texture is base64.
  3337. *
  3338. * @param formatsAvailable defines the list of those format families you have created
  3339. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3340. *
  3341. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3342. * @returns The extension selected.
  3343. */
  3344. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3345. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3346. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3347. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3348. return this._textureFormatInUse = this._texturesSupported[i];
  3349. }
  3350. }
  3351. }
  3352. // actively set format to nothing, to allow this to be called more than once
  3353. // and possibly fail the 2nd time
  3354. this._textureFormatInUse = null;
  3355. return null;
  3356. }
  3357. private _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3358. var gl = this._gl;
  3359. var magFilter = gl.NEAREST;
  3360. var minFilter = gl.NEAREST;
  3361. switch (samplingMode) {
  3362. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  3363. magFilter = gl.LINEAR;
  3364. if (generateMipMaps) {
  3365. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3366. } else {
  3367. minFilter = gl.LINEAR;
  3368. }
  3369. break;
  3370. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  3371. magFilter = gl.LINEAR;
  3372. if (generateMipMaps) {
  3373. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3374. } else {
  3375. minFilter = gl.LINEAR;
  3376. }
  3377. break;
  3378. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  3379. magFilter = gl.NEAREST;
  3380. if (generateMipMaps) {
  3381. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3382. } else {
  3383. minFilter = gl.NEAREST;
  3384. }
  3385. break;
  3386. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  3387. magFilter = gl.NEAREST;
  3388. if (generateMipMaps) {
  3389. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3390. } else {
  3391. minFilter = gl.NEAREST;
  3392. }
  3393. break;
  3394. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  3395. magFilter = gl.NEAREST;
  3396. if (generateMipMaps) {
  3397. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3398. } else {
  3399. minFilter = gl.LINEAR;
  3400. }
  3401. break;
  3402. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  3403. magFilter = gl.NEAREST;
  3404. if (generateMipMaps) {
  3405. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3406. } else {
  3407. minFilter = gl.LINEAR;
  3408. }
  3409. break;
  3410. case Engine.TEXTURE_NEAREST_LINEAR:
  3411. magFilter = gl.NEAREST;
  3412. minFilter = gl.LINEAR;
  3413. break;
  3414. case Engine.TEXTURE_NEAREST_NEAREST:
  3415. magFilter = gl.NEAREST;
  3416. minFilter = gl.NEAREST;
  3417. break;
  3418. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  3419. magFilter = gl.LINEAR;
  3420. if (generateMipMaps) {
  3421. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  3422. } else {
  3423. minFilter = gl.NEAREST;
  3424. }
  3425. break;
  3426. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  3427. magFilter = gl.LINEAR;
  3428. if (generateMipMaps) {
  3429. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3430. } else {
  3431. minFilter = gl.NEAREST;
  3432. }
  3433. break;
  3434. case Engine.TEXTURE_LINEAR_LINEAR:
  3435. magFilter = gl.LINEAR;
  3436. minFilter = gl.LINEAR;
  3437. break;
  3438. case Engine.TEXTURE_LINEAR_NEAREST:
  3439. magFilter = gl.LINEAR;
  3440. minFilter = gl.NEAREST;
  3441. break;
  3442. }
  3443. return {
  3444. min: minFilter,
  3445. mag: magFilter
  3446. }
  3447. }
  3448. private _partialLoadImg(url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  3449. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) {
  3450. var img: HTMLImageElement;
  3451. var onload = () => {
  3452. loadedImages[index] = img;
  3453. (<any>loadedImages)._internalCount++;
  3454. if (scene) {
  3455. scene._removePendingData(img);
  3456. }
  3457. if ((<any>loadedImages)._internalCount === 6) {
  3458. onfinish(loadedImages);
  3459. }
  3460. };
  3461. var onerror = (message?: string, exception?: any) => {
  3462. if (scene) {
  3463. scene._removePendingData(img);
  3464. }
  3465. if (onErrorCallBack) {
  3466. onErrorCallBack(message, exception);
  3467. }
  3468. };
  3469. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  3470. if (scene) {
  3471. scene._addPendingData(img);
  3472. }
  3473. }
  3474. private _cascadeLoadImgs(rootUrl: string, scene: Nullable<Scene>,
  3475. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) {
  3476. var loadedImages: HTMLImageElement[] = [];
  3477. (<any>loadedImages)._internalCount = 0;
  3478. for (let index = 0; index < 6; index++) {
  3479. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  3480. }
  3481. };
  3482. /** @hidden */
  3483. public _createTexture(): WebGLTexture {
  3484. let texture = this._gl.createTexture();
  3485. if (!texture) {
  3486. throw new Error("Unable to create texture");
  3487. }
  3488. return texture;
  3489. }
  3490. /**
  3491. * Usually called from BABYLON.Texture.ts.
  3492. * Passed information to create a WebGLTexture
  3493. * @param urlArg defines a value which contains one of the following:
  3494. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3495. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3496. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3497. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3498. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  3499. * @param scene needed for loading to the correct scene
  3500. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  3501. * @param onLoad optional callback to be called upon successful completion
  3502. * @param onError optional callback to be called upon failure
  3503. * @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
  3504. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3505. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3506. * @param forcedExtension defines the extension to use to pick the right loader
  3507. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3508. */
  3509. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  3510. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3511. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  3512. forcedExtension: Nullable<string> = null): InternalTexture {
  3513. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3514. var fromData = url.substr(0, 5) === "data:";
  3515. var fromBlob = url.substr(0, 5) === "blob:";
  3516. var isBase64 = fromData && url.indexOf("base64") !== -1;
  3517. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3518. // establish the file extension, if possible
  3519. var lastDot = url.lastIndexOf('.');
  3520. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  3521. let loader: Nullable<IInternalTextureLoader> = null;
  3522. for (let availableLoader of Engine._TextureLoaders) {
  3523. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  3524. loader = availableLoader;
  3525. break;
  3526. }
  3527. }
  3528. if (loader) {
  3529. url = loader.transformUrl(url, this._textureFormatInUse);
  3530. }
  3531. if (scene) {
  3532. scene._addPendingData(texture);
  3533. }
  3534. texture.url = url;
  3535. texture.generateMipMaps = !noMipmap;
  3536. texture.samplingMode = samplingMode;
  3537. texture.invertY = invertY;
  3538. if (!this._doNotHandleContextLost) {
  3539. // Keep a link to the buffer only if we plan to handle context lost
  3540. texture._buffer = buffer;
  3541. }
  3542. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3543. if (onLoad && !fallback) {
  3544. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3545. }
  3546. if (!fallback) this._internalTexturesCache.push(texture);
  3547. let onInternalError = (message?: string, exception?: any) => {
  3548. if (scene) {
  3549. scene._removePendingData(texture);
  3550. }
  3551. let customFallback = false;
  3552. if (loader) {
  3553. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  3554. if (fallbackUrl) {
  3555. // Add Back
  3556. customFallback = true;
  3557. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3558. }
  3559. }
  3560. if (!customFallback) {
  3561. if (onLoadObserver) {
  3562. texture.onLoadedObservable.remove(onLoadObserver);
  3563. }
  3564. if (Tools.UseFallbackTexture) {
  3565. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3566. }
  3567. }
  3568. if (onError) {
  3569. onError(message || "Unknown error", exception);
  3570. }
  3571. }
  3572. // processing for non-image formats
  3573. if (loader) {
  3574. var callback = (data: string | ArrayBuffer) => {
  3575. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => {
  3576. this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  3577. done();
  3578. return false;
  3579. },
  3580. samplingMode);
  3581. });
  3582. }
  3583. if (!buffer) {
  3584. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3585. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  3586. });
  3587. } else {
  3588. callback(buffer as ArrayBuffer);
  3589. }
  3590. } else {
  3591. var onload = (img: HTMLImageElement) => {
  3592. if (fromBlob && !this._doNotHandleContextLost) {
  3593. // We need to store the image if we need to rebuild the texture
  3594. // in case of a webgl context lost
  3595. texture._buffer = img;
  3596. }
  3597. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3598. let gl = this._gl;
  3599. var isPot = (img.width === potWidth && img.height === potHeight);
  3600. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3601. if (isPot) {
  3602. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3603. return false;
  3604. }
  3605. let maxTextureSize = this._caps.maxTextureSize;
  3606. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  3607. this._prepareWorkingCanvas();
  3608. if (!this._workingCanvas || !this._workingContext) {
  3609. return false;
  3610. }
  3611. this._workingCanvas.width = potWidth;
  3612. this._workingCanvas.height = potHeight;
  3613. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3614. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3615. texture.width = potWidth;
  3616. texture.height = potHeight;
  3617. return false;
  3618. } else {
  3619. // Using shaders when possible to rescale because canvas.drawImage is lossy
  3620. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3621. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3622. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3627. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3628. this._releaseTexture(source);
  3629. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3630. continuationCallback();
  3631. });
  3632. }
  3633. return true;
  3634. }, samplingMode);
  3635. };
  3636. if (!fromData || isBase64) {
  3637. if (buffer instanceof HTMLImageElement) {
  3638. onload(buffer);
  3639. } else {
  3640. Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  3641. }
  3642. }
  3643. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3644. Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  3645. }
  3646. else {
  3647. onload(<HTMLImageElement>buffer);
  3648. }
  3649. }
  3650. return texture;
  3651. }
  3652. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3653. let rtt = this.createRenderTargetTexture({
  3654. width: destination.width,
  3655. height: destination.height,
  3656. }, {
  3657. generateMipMaps: false,
  3658. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3659. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  3660. generateDepthBuffer: false,
  3661. generateStencilBuffer: false
  3662. }
  3663. );
  3664. if (!this._rescalePostProcess) {
  3665. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3666. }
  3667. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3668. this._rescalePostProcess.onApply = function (effect) {
  3669. effect._bindTexture("textureSampler", source);
  3670. }
  3671. let hostingScene = scene;
  3672. if (!hostingScene) {
  3673. hostingScene = this.scenes[this.scenes.length - 1];
  3674. }
  3675. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3676. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3677. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3678. this.unBindFramebuffer(rtt);
  3679. this._releaseTexture(rtt);
  3680. if (onComplete) {
  3681. onComplete();
  3682. }
  3683. });
  3684. }
  3685. /**
  3686. * Update a raw texture
  3687. * @param texture defines the texture to update
  3688. * @param data defines the data to store in the texture
  3689. * @param format defines the format of the data
  3690. * @param invertY defines if data must be stored with Y axis inverted
  3691. * @param compression defines the compression used (null by default)
  3692. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3693. */
  3694. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void { if (!texture) {
  3695. return;
  3696. }
  3697. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  3698. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3699. // babylon's internalFormat but gl's texImage2D format
  3700. var internalFormat = this._getInternalFormat(format);
  3701. var textureType = this._getWebGLTextureType(type);
  3702. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3703. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3704. if (!this._doNotHandleContextLost) {
  3705. texture._bufferView = data;
  3706. texture.format = format;
  3707. texture.type = type;
  3708. texture.invertY = invertY;
  3709. texture._compression = compression;
  3710. }
  3711. if (texture.width % 4 !== 0) {
  3712. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3713. }
  3714. if (compression && data) {
  3715. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3716. } else {
  3717. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3718. }
  3719. if (texture.generateMipMaps) {
  3720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3721. }
  3722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3723. // this.resetTextureCache();
  3724. texture.isReady = true;
  3725. }
  3726. /**
  3727. * Creates a raw texture
  3728. * @param data defines the data to store in the texture
  3729. * @param width defines the width of the texture
  3730. * @param height defines the height of the texture
  3731. * @param format defines the format of the data
  3732. * @param generateMipMaps defines if the engine should generate the mip levels
  3733. * @param invertY defines if data must be stored with Y axis inverted
  3734. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3735. * @param compression defines the compression used (null by default)
  3736. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3737. * @returns the raw texture inside an InternalTexture
  3738. */
  3739. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3740. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3741. texture.baseWidth = width;
  3742. texture.baseHeight = height;
  3743. texture.width = width;
  3744. texture.height = height;
  3745. texture.format = format;
  3746. texture.generateMipMaps = generateMipMaps;
  3747. texture.samplingMode = samplingMode;
  3748. texture.invertY = invertY;
  3749. texture._compression = compression;
  3750. texture.type = type;
  3751. if (!this._doNotHandleContextLost) {
  3752. texture._bufferView = data;
  3753. }
  3754. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3755. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3756. // Filters
  3757. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  3758. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3760. if (generateMipMaps) {
  3761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3762. }
  3763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3764. this._internalTexturesCache.push(texture);
  3765. return texture;
  3766. }
  3767. private _unpackFlipYCached: Nullable<boolean> = null;
  3768. /** @hidden */
  3769. public _unpackFlipY(value: boolean) {
  3770. if (this._unpackFlipYCached !== value) {
  3771. this._unpackFlipYCached = value;
  3772. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  3773. }
  3774. }
  3775. /** @hidden */
  3776. public _getUnpackAlignement(): number {
  3777. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  3778. }
  3779. /**
  3780. * Creates a dynamic texture
  3781. * @param width defines the width of the texture
  3782. * @param height defines the height of the texture
  3783. * @param generateMipMaps defines if the engine should generate the mip levels
  3784. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3785. * @returns the dynamic texture inside an InternalTexture
  3786. */
  3787. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3788. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  3789. texture.baseWidth = width;
  3790. texture.baseHeight = height;
  3791. if (generateMipMaps) {
  3792. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3793. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3794. }
  3795. // this.resetTextureCache();
  3796. texture.width = width;
  3797. texture.height = height;
  3798. texture.isReady = false;
  3799. texture.generateMipMaps = generateMipMaps;
  3800. texture.samplingMode = samplingMode;
  3801. this.updateTextureSamplingMode(samplingMode, texture);
  3802. this._internalTexturesCache.push(texture);
  3803. return texture;
  3804. }
  3805. /**
  3806. * Update the sampling mode of a given texture
  3807. * @param samplingMode defines the required sampling mode
  3808. * @param texture defines the texture to update
  3809. */
  3810. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3811. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  3812. if (texture.isCube) {
  3813. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3814. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3815. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3816. } else if (texture.is3D) {
  3817. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3818. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3819. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3820. } else {
  3821. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3822. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3823. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3824. }
  3825. texture.samplingMode = samplingMode;
  3826. }
  3827. /**
  3828. * Update the content of a dynamic texture
  3829. * @param texture defines the texture to update
  3830. * @param canvas defines the canvas containing the source
  3831. * @param invertY defines if data must be stored with Y axis inverted
  3832. * @param premulAlpha defines if alpha is stored as premultiplied
  3833. * @param format defines the format of the data
  3834. */
  3835. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  3836. if (!texture) {
  3837. return;
  3838. }
  3839. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3840. this._unpackFlipY(invertY);
  3841. if (premulAlpha) {
  3842. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3843. }
  3844. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3846. if (texture.generateMipMaps) {
  3847. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3848. }
  3849. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3850. if (premulAlpha) {
  3851. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3852. }
  3853. texture.isReady = true;
  3854. }
  3855. /**
  3856. * Update a video texture
  3857. * @param texture defines the texture to update
  3858. * @param video defines the video element to use
  3859. * @param invertY defines if data must be stored with Y axis inverted
  3860. */
  3861. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  3862. if (!texture || texture._isDisabled) {
  3863. return;
  3864. }
  3865. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3866. this._unpackFlipY(!invertY); // Video are upside down by default
  3867. try {
  3868. // Testing video texture support
  3869. if (this._videoTextureSupported === undefined) {
  3870. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3871. if (this._gl.getError() !== 0) {
  3872. this._videoTextureSupported = false;
  3873. } else {
  3874. this._videoTextureSupported = true;
  3875. }
  3876. }
  3877. // Copy video through the current working canvas if video texture is not supported
  3878. if (!this._videoTextureSupported) {
  3879. if (!texture._workingCanvas) {
  3880. texture._workingCanvas = document.createElement("canvas");
  3881. let context = texture._workingCanvas.getContext("2d");
  3882. if (!context) {
  3883. throw new Error("Unable to get 2d context");
  3884. }
  3885. texture._workingContext = context;
  3886. texture._workingCanvas.width = texture.width;
  3887. texture._workingCanvas.height = texture.height;
  3888. }
  3889. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  3890. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3891. } else {
  3892. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3893. }
  3894. if (texture.generateMipMaps) {
  3895. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3896. }
  3897. if (!wasPreviouslyBound) {
  3898. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3899. }
  3900. // this.resetTextureCache();
  3901. texture.isReady = true;
  3902. } catch (ex) {
  3903. // Something unexpected
  3904. // Let's disable the texture
  3905. texture._isDisabled = true;
  3906. }
  3907. }
  3908. /**
  3909. * Updates a depth texture Comparison Mode and Function.
  3910. * If the comparison Function is equal to 0, the mode will be set to none.
  3911. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  3912. * @param texture The texture to set the comparison function for
  3913. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  3914. */
  3915. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3916. if (this.webGLVersion === 1) {
  3917. Tools.Error("WebGL 1 does not support texture comparison.");
  3918. return;
  3919. }
  3920. var gl = this._gl;
  3921. if (texture.isCube) {
  3922. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3923. if (comparisonFunction === 0) {
  3924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3926. }
  3927. else {
  3928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3930. }
  3931. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3932. } else {
  3933. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3934. if (comparisonFunction === 0) {
  3935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3937. }
  3938. else {
  3939. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3940. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3941. }
  3942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3943. }
  3944. texture._comparisonFunction = comparisonFunction;
  3945. }
  3946. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3947. var width = (<{ width: number, height: number }>size).width || <number>size;
  3948. var height = (<{ width: number, height: number }>size).height || <number>size;
  3949. internalTexture.baseWidth = width;
  3950. internalTexture.baseHeight = height;
  3951. internalTexture.width = width;
  3952. internalTexture.height = height;
  3953. internalTexture.isReady = true;
  3954. internalTexture.samples = 1;
  3955. internalTexture.generateMipMaps = false;
  3956. internalTexture._generateDepthBuffer = true;
  3957. internalTexture._generateStencilBuffer = generateStencil;
  3958. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  3959. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3960. internalTexture._comparisonFunction = comparisonFunction;
  3961. var gl = this._gl;
  3962. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3963. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  3964. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3965. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3966. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3967. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3968. if (comparisonFunction === 0) {
  3969. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3970. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3971. }
  3972. else {
  3973. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3974. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3975. }
  3976. }
  3977. /**
  3978. * Creates a depth stencil texture.
  3979. * This is only available in WebGL 2 or with the depth texture extension available.
  3980. * @param size The size of face edge in the texture.
  3981. * @param options The options defining the texture.
  3982. * @returns The texture
  3983. */
  3984. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3985. if (options.isCube) {
  3986. let width = (<{ width: number, height: number }>size).width || <number>size;
  3987. return this._createDepthStencilCubeTexture(width, options);
  3988. }
  3989. else {
  3990. return this._createDepthStencilTexture(size, options);
  3991. }
  3992. }
  3993. /**
  3994. * Creates a depth stencil texture.
  3995. * This is only available in WebGL 2 or with the depth texture extension available.
  3996. * @param size The size of face edge in the texture.
  3997. * @param options The options defining the texture.
  3998. * @returns The texture
  3999. */
  4000. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  4001. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  4002. if (!this._caps.depthTextureExtension) {
  4003. Tools.Error("Depth texture is not supported by your browser or hardware.");
  4004. return internalTexture;
  4005. }
  4006. var internalOptions = {
  4007. bilinearFiltering: false,
  4008. comparisonFunction: 0,
  4009. generateStencil: false,
  4010. ...options
  4011. }
  4012. var gl = this._gl;
  4013. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  4014. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4015. if (this.webGLVersion > 1) {
  4016. if (internalOptions.generateStencil) {
  4017. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4018. }
  4019. else {
  4020. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4021. }
  4022. }
  4023. else {
  4024. if (internalOptions.generateStencil) {
  4025. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4026. }
  4027. else {
  4028. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4029. }
  4030. }
  4031. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4032. return internalTexture;
  4033. }
  4034. /**
  4035. * Creates a depth stencil cube texture.
  4036. * This is only available in WebGL 2.
  4037. * @param size The size of face edge in the cube texture.
  4038. * @param options The options defining the cube texture.
  4039. * @returns The cube texture
  4040. */
  4041. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  4042. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4043. internalTexture.isCube = true;
  4044. if (this.webGLVersion === 1) {
  4045. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4046. return internalTexture;
  4047. }
  4048. var internalOptions = {
  4049. bilinearFiltering: false,
  4050. comparisonFunction: 0,
  4051. generateStencil: false,
  4052. ...options
  4053. }
  4054. var gl = this._gl;
  4055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4056. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4057. // Create the depth/stencil buffer
  4058. for (var face = 0; face < 6; face++) {
  4059. if (internalOptions.generateStencil) {
  4060. 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);
  4061. }
  4062. else {
  4063. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4064. }
  4065. }
  4066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4067. return internalTexture;
  4068. }
  4069. /**
  4070. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4071. * @param renderTarget The render target to set the frame buffer for
  4072. */
  4073. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4074. // Create the framebuffer
  4075. var internalTexture = renderTarget.getInternalTexture();
  4076. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4077. return;
  4078. }
  4079. var gl = this._gl;
  4080. var depthStencilTexture = renderTarget.depthStencilTexture;
  4081. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4082. if (depthStencilTexture.isCube) {
  4083. if (depthStencilTexture._generateStencilBuffer) {
  4084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4085. }
  4086. else {
  4087. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4088. }
  4089. }
  4090. else {
  4091. if (depthStencilTexture._generateStencilBuffer) {
  4092. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4093. }
  4094. else {
  4095. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4096. }
  4097. }
  4098. this.bindUnboundFramebuffer(null);
  4099. }
  4100. /**
  4101. * Creates a new render target texture
  4102. * @param size defines the size of the texture
  4103. * @param options defines the options used to create the texture
  4104. * @returns a new render target texture stored in an InternalTexture
  4105. */
  4106. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4107. let fullOptions = new RenderTargetCreationOptions();
  4108. if (options !== undefined && typeof options === "object") {
  4109. fullOptions.generateMipMaps = options.generateMipMaps;
  4110. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4111. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4112. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4113. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4114. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4115. } else {
  4116. fullOptions.generateMipMaps = <boolean>options;
  4117. fullOptions.generateDepthBuffer = true;
  4118. fullOptions.generateStencilBuffer = false;
  4119. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4120. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4121. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4122. }
  4123. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4124. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4125. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4126. }
  4127. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4128. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4129. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4130. }
  4131. var gl = this._gl;
  4132. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4133. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4134. var width = (<{ width: number, height: number }>size).width || <number>size;
  4135. var height = (<{ width: number, height: number }>size).height || <number>size;
  4136. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  4137. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4139. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4140. }
  4141. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4145. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4146. // Create the framebuffer
  4147. var currentFrameBuffer = this._currentFramebuffer;
  4148. var framebuffer = gl.createFramebuffer();
  4149. this.bindUnboundFramebuffer(framebuffer);
  4150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4151. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4152. if (fullOptions.generateMipMaps) {
  4153. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4154. }
  4155. // Unbind
  4156. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4157. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4158. this.bindUnboundFramebuffer(currentFrameBuffer);
  4159. texture._framebuffer = framebuffer;
  4160. texture.baseWidth = width;
  4161. texture.baseHeight = height;
  4162. texture.width = width;
  4163. texture.height = height;
  4164. texture.isReady = true;
  4165. texture.samples = 1;
  4166. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4167. texture.samplingMode = fullOptions.samplingMode;
  4168. texture.type = fullOptions.type;
  4169. texture.format = fullOptions.format;
  4170. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4171. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4172. // this.resetTextureCache();
  4173. this._internalTexturesCache.push(texture);
  4174. return texture;
  4175. }
  4176. /**
  4177. * Create a multi render target texture
  4178. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4179. * @param size defines the size of the texture
  4180. * @param options defines the creation options
  4181. * @returns the cube texture as an InternalTexture
  4182. */
  4183. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4184. var generateMipMaps = false;
  4185. var generateDepthBuffer = true;
  4186. var generateStencilBuffer = false;
  4187. var generateDepthTexture = false;
  4188. var textureCount = 1;
  4189. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4190. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4191. var types = new Array<number>();
  4192. var samplingModes = new Array<number>();
  4193. if (options !== undefined) {
  4194. generateMipMaps = options.generateMipMaps === undefined ? false: options.generateMipMaps;
  4195. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4196. generateStencilBuffer = options.generateStencilBuffer === undefined ? false: options.generateStencilBuffer;
  4197. generateDepthTexture = options.generateDepthTexture === undefined ? false: options.generateDepthTexture;
  4198. textureCount = options.textureCount || 1;
  4199. if (options.types) {
  4200. types = options.types;
  4201. }
  4202. if (options.samplingModes) {
  4203. samplingModes = options.samplingModes;
  4204. }
  4205. }
  4206. var gl = this._gl;
  4207. // Create the framebuffer
  4208. var framebuffer = gl.createFramebuffer();
  4209. this.bindUnboundFramebuffer(framebuffer);
  4210. var width = size.width || size;
  4211. var height = size.height || size;
  4212. var textures = [];
  4213. var attachments = []
  4214. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4215. for (var i = 0; i < textureCount; i++) {
  4216. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4217. var type = types[i] || defaultType;
  4218. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4219. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4220. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4221. }
  4222. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4223. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4224. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4225. }
  4226. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4227. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4228. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4229. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4230. }
  4231. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4232. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4233. textures.push(texture);
  4234. attachments.push(attachment);
  4235. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4236. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4241. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4242. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4243. if (generateMipMaps) {
  4244. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4245. }
  4246. // Unbind
  4247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4248. texture._framebuffer = framebuffer;
  4249. texture._depthStencilBuffer = depthStencilBuffer;
  4250. texture.baseWidth = width;
  4251. texture.baseHeight = height;
  4252. texture.width = width;
  4253. texture.height = height;
  4254. texture.isReady = true;
  4255. texture.samples = 1;
  4256. texture.generateMipMaps = generateMipMaps;
  4257. texture.samplingMode = samplingMode;
  4258. texture.type = type;
  4259. texture._generateDepthBuffer = generateDepthBuffer;
  4260. texture._generateStencilBuffer = generateStencilBuffer;
  4261. texture._attachments = attachments;
  4262. this._internalTexturesCache.push(texture);
  4263. }
  4264. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4265. // Depth texture
  4266. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4267. gl.activeTexture(gl.TEXTURE0);
  4268. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4273. gl.texImage2D(
  4274. gl.TEXTURE_2D,
  4275. 0,
  4276. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4277. width,
  4278. height,
  4279. 0,
  4280. gl.DEPTH_COMPONENT,
  4281. gl.UNSIGNED_SHORT,
  4282. null
  4283. );
  4284. gl.framebufferTexture2D(
  4285. gl.FRAMEBUFFER,
  4286. gl.DEPTH_ATTACHMENT,
  4287. gl.TEXTURE_2D,
  4288. depthTexture._webGLTexture,
  4289. 0
  4290. );
  4291. depthTexture._framebuffer = framebuffer;
  4292. depthTexture.baseWidth = width;
  4293. depthTexture.baseHeight = height;
  4294. depthTexture.width = width;
  4295. depthTexture.height = height;
  4296. depthTexture.isReady = true;
  4297. depthTexture.samples = 1;
  4298. depthTexture.generateMipMaps = generateMipMaps;
  4299. depthTexture.samplingMode = gl.NEAREST;
  4300. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4301. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4302. textures.push(depthTexture)
  4303. this._internalTexturesCache.push(depthTexture);
  4304. }
  4305. gl.drawBuffers(attachments);
  4306. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4307. this.bindUnboundFramebuffer(null);
  4308. this.resetTextureCache();
  4309. return textures;
  4310. }
  4311. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4312. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4313. var gl = this._gl;
  4314. // Create the depth/stencil buffer
  4315. if (generateStencilBuffer) {
  4316. depthStencilBuffer = gl.createRenderbuffer();
  4317. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4318. if (samples > 1) {
  4319. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4320. } else {
  4321. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4322. }
  4323. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4324. }
  4325. else if (generateDepthBuffer) {
  4326. depthStencilBuffer = gl.createRenderbuffer();
  4327. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4328. if (samples > 1) {
  4329. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4330. } else {
  4331. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4332. }
  4333. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4334. }
  4335. return depthStencilBuffer;
  4336. }
  4337. /**
  4338. * Updates the sample count of a render target texture
  4339. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4340. * @param texture defines the texture to update
  4341. * @param samples defines the sample count to set
  4342. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4343. */
  4344. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4345. if (this.webGLVersion < 2 || !texture) {
  4346. return 1;
  4347. }
  4348. if (texture.samples === samples) {
  4349. return samples;
  4350. }
  4351. var gl = this._gl;
  4352. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4353. // Dispose previous render buffers
  4354. if (texture._depthStencilBuffer) {
  4355. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4356. texture._depthStencilBuffer = null;
  4357. }
  4358. if (texture._MSAAFramebuffer) {
  4359. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4360. texture._MSAAFramebuffer = null;
  4361. }
  4362. if (texture._MSAARenderBuffer) {
  4363. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4364. texture._MSAARenderBuffer = null;
  4365. }
  4366. if (samples > 1) {
  4367. let framebuffer = gl.createFramebuffer();
  4368. if (!framebuffer) {
  4369. throw new Error("Unable to create multi sampled framebuffer");
  4370. }
  4371. texture._MSAAFramebuffer = framebuffer;
  4372. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4373. var colorRenderbuffer = gl.createRenderbuffer();
  4374. if (!colorRenderbuffer) {
  4375. throw new Error("Unable to create multi sampled framebuffer");
  4376. }
  4377. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4378. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4379. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4380. texture._MSAARenderBuffer = colorRenderbuffer;
  4381. } else {
  4382. this.bindUnboundFramebuffer(texture._framebuffer);
  4383. }
  4384. texture.samples = samples;
  4385. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4386. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4387. this.bindUnboundFramebuffer(null);
  4388. return samples;
  4389. }
  4390. /**
  4391. * Update the sample count for a given multiple render target texture
  4392. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4393. * @param textures defines the textures to update
  4394. * @param samples defines the sample count to set
  4395. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4396. */
  4397. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4398. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4399. return 1;
  4400. }
  4401. if (textures[0].samples === samples) {
  4402. return samples;
  4403. }
  4404. var gl = this._gl;
  4405. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4406. // Dispose previous render buffers
  4407. if (textures[0]._depthStencilBuffer) {
  4408. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4409. textures[0]._depthStencilBuffer = null;
  4410. }
  4411. if (textures[0]._MSAAFramebuffer) {
  4412. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4413. textures[0]._MSAAFramebuffer = null;
  4414. }
  4415. for (var i = 0; i < textures.length; i++) {
  4416. if (textures[i]._MSAARenderBuffer) {
  4417. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4418. textures[i]._MSAARenderBuffer = null;
  4419. }
  4420. }
  4421. if (samples > 1) {
  4422. let framebuffer = gl.createFramebuffer();
  4423. if (!framebuffer) {
  4424. throw new Error("Unable to create multi sampled framebuffer");
  4425. }
  4426. this.bindUnboundFramebuffer(framebuffer);
  4427. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4428. var attachments = [];
  4429. for (var i = 0; i < textures.length; i++) {
  4430. var texture = textures[i];
  4431. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4432. var colorRenderbuffer = gl.createRenderbuffer();
  4433. if (!colorRenderbuffer) {
  4434. throw new Error("Unable to create multi sampled framebuffer");
  4435. }
  4436. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4437. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4438. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4439. texture._MSAAFramebuffer = framebuffer;
  4440. texture._MSAARenderBuffer = colorRenderbuffer;
  4441. texture.samples = samples;
  4442. texture._depthStencilBuffer = depthStencilBuffer;
  4443. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4444. attachments.push(attachment);
  4445. }
  4446. gl.drawBuffers(attachments);
  4447. } else {
  4448. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4449. }
  4450. this.bindUnboundFramebuffer(null);
  4451. return samples;
  4452. }
  4453. /** @hidden */
  4454. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  4455. var gl = this._gl;
  4456. var target = gl.TEXTURE_2D;
  4457. if (texture.isCube) {
  4458. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4459. }
  4460. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4461. }
  4462. /** @hidden */
  4463. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4464. var gl = this._gl;
  4465. var textureType = this._getWebGLTextureType(texture.type);
  4466. var format = this._getInternalFormat(texture.format);
  4467. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4468. this._unpackFlipY(texture.invertY);
  4469. var target = gl.TEXTURE_2D;
  4470. if (texture.isCube) {
  4471. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4472. }
  4473. const lodMaxWidth = Math.round(Scalar.Log2(texture.width));
  4474. const lodMaxHeight = Math.round(Scalar.Log2(texture.height));
  4475. const width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  4476. const height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  4477. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  4478. }
  4479. /** @hidden */
  4480. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4481. var gl = this._gl;
  4482. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4483. this._bindTextureDirectly(bindTarget, texture, true);
  4484. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  4485. this._bindTextureDirectly(bindTarget, null, true);
  4486. }
  4487. /** @hidden */
  4488. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  4489. var gl = this._gl;
  4490. var textureType = this._getWebGLTextureType(texture.type);
  4491. var format = this._getInternalFormat(texture.format);
  4492. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4493. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4494. this._bindTextureDirectly(bindTarget, texture, true);
  4495. this._unpackFlipY(texture.invertY);
  4496. var target = gl.TEXTURE_2D;
  4497. if (texture.isCube) {
  4498. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4499. }
  4500. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  4501. this._bindTextureDirectly(bindTarget, null, true);
  4502. }
  4503. /**
  4504. * Creates a new render target cube texture
  4505. * @param size defines the size of the texture
  4506. * @param options defines the options used to create the texture
  4507. * @returns a new render target cube texture stored in an InternalTexture
  4508. */
  4509. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4510. let fullOptions = {
  4511. generateMipMaps: true,
  4512. generateDepthBuffer: true,
  4513. generateStencilBuffer: false,
  4514. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4515. samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4516. format: Engine.TEXTUREFORMAT_RGBA,
  4517. ...options
  4518. };
  4519. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4520. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4521. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4522. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4523. }
  4524. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4525. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4526. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4527. }
  4528. var gl = this._gl
  4529. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4530. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4531. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  4532. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4533. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4534. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4535. }
  4536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4540. for (var face = 0; face < 6; face++) {
  4541. 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);
  4542. }
  4543. // Create the framebuffer
  4544. var framebuffer = gl.createFramebuffer();
  4545. this.bindUnboundFramebuffer(framebuffer);
  4546. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4547. // MipMaps
  4548. if (fullOptions.generateMipMaps) {
  4549. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4550. }
  4551. // Unbind
  4552. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4553. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4554. this.bindUnboundFramebuffer(null);
  4555. texture._framebuffer = framebuffer;
  4556. texture.width = size;
  4557. texture.height = size;
  4558. texture.isReady = true;
  4559. texture.isCube = true;
  4560. texture.samples = 1;
  4561. texture.generateMipMaps = fullOptions.generateMipMaps;
  4562. texture.samplingMode = fullOptions.samplingMode;
  4563. texture.type = fullOptions.type;
  4564. texture.format = fullOptions.format;
  4565. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4566. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4567. this._internalTexturesCache.push(texture);
  4568. return texture;
  4569. }
  4570. /**
  4571. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4572. * @param rootUrl defines the url where the file to load is located
  4573. * @param scene defines the current scene
  4574. * @param lodScale defines scale to apply to the mip map selection
  4575. * @param lodOffset defines offset to apply to the mip map selection
  4576. * @param onLoad defines an optional callback raised when the texture is loaded
  4577. * @param onError defines an optional callback raised if there is an issue to load the texture
  4578. * @param format defines the format of the data
  4579. * @param forcedExtension defines the extension to use to pick the right loader
  4580. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  4581. * @returns the cube texture as an InternalTexture
  4582. */
  4583. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  4584. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4585. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null,
  4586. createPolynomials: boolean = true): InternalTexture {
  4587. var callback = (loadData: any) => {
  4588. if (!loadData) {
  4589. if (onLoad) {
  4590. onLoad(null);
  4591. }
  4592. return;
  4593. }
  4594. let texture = loadData.texture as InternalTexture;
  4595. if (!createPolynomials) {
  4596. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  4597. }
  4598. else if(loadData.info.sphericalPolynomial){
  4599. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  4600. }
  4601. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4602. if (this._caps.textureLOD) {
  4603. // Do not add extra process if texture lod is supported.
  4604. if (onLoad) {
  4605. onLoad(texture);
  4606. }
  4607. return;
  4608. }
  4609. const mipSlices = 3;
  4610. var gl = this._gl;
  4611. const width = loadData.width;
  4612. if (!width) {
  4613. return;
  4614. }
  4615. const textures: BaseTexture[] = [];
  4616. for (let i = 0; i < mipSlices; i++) {
  4617. //compute LOD from even spacing in smoothness (matching shader calculation)
  4618. let smoothness = i / (mipSlices - 1);
  4619. let roughness = 1 - smoothness;
  4620. let minLODIndex = lodOffset; // roughness = 0
  4621. let maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  4622. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4623. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4624. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4625. glTextureFromLod.type = texture.type;
  4626. glTextureFromLod.format = texture.format;
  4627. glTextureFromLod.width = Math.pow(2, Math.max( Scalar.Log2(width) - mipmapIndex, 0));
  4628. glTextureFromLod.height = glTextureFromLod.width;
  4629. glTextureFromLod.isCube = true;
  4630. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4635. if (loadData.isDDS) {
  4636. var info: DDSInfo = loadData.info;
  4637. var data: any = loadData.data;
  4638. this._unpackFlipY(info.isCompressed);
  4639. DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  4640. }
  4641. else {
  4642. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  4643. }
  4644. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4645. // Wrap in a base texture for easy binding.
  4646. const lodTexture = new BaseTexture(scene);
  4647. lodTexture.isCube = true;
  4648. lodTexture._texture = glTextureFromLod;
  4649. glTextureFromLod.isReady = true;
  4650. textures.push(lodTexture);
  4651. }
  4652. texture._lodTextureHigh = textures[2];
  4653. texture._lodTextureMid = textures[1];
  4654. texture._lodTextureLow = textures[0];
  4655. if (onLoad) {
  4656. onLoad(texture);
  4657. }
  4658. };
  4659. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  4660. }
  4661. /**
  4662. * Creates a cube texture
  4663. * @param rootUrl defines the url where the files to load is located
  4664. * @param scene defines the current scene
  4665. * @param files defines the list of files to load (1 per face)
  4666. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4667. * @param onLoad defines an optional callback raised when the texture is loaded
  4668. * @param onError defines an optional callback raised if there is an issue to load the texture
  4669. * @param format defines the format of the data
  4670. * @param forcedExtension defines the extension to use to pick the right loader
  4671. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4672. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  4673. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  4674. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  4675. * @returns the cube texture as an InternalTexture
  4676. */
  4677. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null): InternalTexture {
  4678. var gl = this._gl;
  4679. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4680. texture.isCube = true;
  4681. texture.url = rootUrl;
  4682. texture.generateMipMaps = !noMipmap;
  4683. texture._lodGenerationScale = lodScale;
  4684. texture._lodGenerationOffset = lodOffset;
  4685. if (!this._doNotHandleContextLost) {
  4686. texture._extension = forcedExtension;
  4687. texture._files = files;
  4688. }
  4689. var lastDot = rootUrl.lastIndexOf('.');
  4690. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4691. let loader: Nullable<IInternalTextureLoader> = null;
  4692. for (let availableLoader of Engine._TextureLoaders) {
  4693. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  4694. loader = availableLoader;
  4695. break;
  4696. }
  4697. }
  4698. let onInternalError = (request?: XMLHttpRequest, exception?: any) => {
  4699. if (loader) {
  4700. const fallbackUrl = loader.getFallbackTextureUrl(rootUrl, this._textureFormatInUse);
  4701. if (fallbackUrl) {
  4702. this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  4703. }
  4704. }
  4705. if (onError && request) {
  4706. onError(request.status + " " + request.statusText, exception);
  4707. }
  4708. }
  4709. if (loader) {
  4710. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  4711. const onloaddata = (data: any) => {
  4712. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4713. loader!.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  4714. };
  4715. if (files && files.length === 6) {
  4716. if (loader.supportCascades) {
  4717. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  4718. }
  4719. else if (onError) {
  4720. onError("Textures type does not support cascades.");
  4721. }
  4722. }
  4723. else {
  4724. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  4725. }
  4726. }
  4727. else {
  4728. if (!files) {
  4729. throw new Error("Cannot load cubemap because files were not defined");
  4730. }
  4731. this._cascadeLoadImgs(rootUrl, scene, imgs => {
  4732. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4733. var height = width;
  4734. this._prepareWorkingCanvas();
  4735. if (!this._workingCanvas || !this._workingContext) {
  4736. return;
  4737. }
  4738. this._workingCanvas.width = width;
  4739. this._workingCanvas.height = height;
  4740. var faces = [
  4741. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4742. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4743. ];
  4744. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4745. this._unpackFlipY(false);
  4746. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4747. for (var index = 0; index < faces.length; index++) {
  4748. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4749. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4750. }
  4751. if (!noMipmap) {
  4752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4753. }
  4754. this._setCubeMapTextureParams(!noMipmap);
  4755. texture.width = width;
  4756. texture.height = height;
  4757. texture.isReady = true;
  4758. if (format) {
  4759. texture.format = format;
  4760. }
  4761. texture.onLoadedObservable.notifyObservers(texture);
  4762. texture.onLoadedObservable.clear();
  4763. if (onLoad) {
  4764. onLoad();
  4765. }
  4766. }, files, onError);
  4767. }
  4768. this._internalTexturesCache.push(texture);
  4769. return texture;
  4770. }
  4771. /**
  4772. * @hidden
  4773. */
  4774. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  4775. var gl = this._gl;
  4776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4781. // this.resetTextureCache();
  4782. }
  4783. /**
  4784. * Update a raw cube texture
  4785. * @param texture defines the texture to udpdate
  4786. * @param data defines the data to store
  4787. * @param format defines the data format
  4788. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4789. * @param invertY defines if data must be stored with Y axis inverted
  4790. * @param compression defines the compression used (null by default)
  4791. * @param level defines which level of the texture to update
  4792. */
  4793. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4794. texture._bufferViewArray = data;
  4795. texture.format = format;
  4796. texture.type = type;
  4797. texture.invertY = invertY;
  4798. texture._compression = compression;
  4799. var gl = this._gl;
  4800. var textureType = this._getWebGLTextureType(type);
  4801. var internalFormat = this._getInternalFormat(format);
  4802. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4803. var needConversion = false;
  4804. if (internalFormat === gl.RGB) {
  4805. internalFormat = gl.RGBA;
  4806. needConversion = true;
  4807. }
  4808. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4809. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4810. if (texture.width % 4 !== 0) {
  4811. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4812. }
  4813. // Data are known to be in +X +Y +Z -X -Y -Z
  4814. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4815. let faceData = data[faceIndex];
  4816. if (compression) {
  4817. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4818. } else {
  4819. if (needConversion) {
  4820. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4821. }
  4822. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4823. }
  4824. }
  4825. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4826. if (isPot && texture.generateMipMaps && level === 0) {
  4827. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4828. }
  4829. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4830. // this.resetTextureCache();
  4831. texture.isReady = true;
  4832. }
  4833. /**
  4834. * Creates a new raw cube texture
  4835. * @param data defines the array of data to use to create each face
  4836. * @param size defines the size of the textures
  4837. * @param format defines the format of the data
  4838. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4839. * @param generateMipMaps defines if the engine should generate the mip levels
  4840. * @param invertY defines if data must be stored with Y axis inverted
  4841. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4842. * @param compression defines the compression used (null by default)
  4843. * @returns the cube texture as an InternalTexture
  4844. */
  4845. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4846. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4847. compression: Nullable<string> = null): InternalTexture {
  4848. var gl = this._gl;
  4849. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4850. texture.isCube = true;
  4851. texture.format = format;
  4852. texture.type = type;
  4853. if (!this._doNotHandleContextLost) {
  4854. texture._bufferViewArray = data;
  4855. }
  4856. var textureType = this._getWebGLTextureType(type);
  4857. var internalFormat = this._getInternalFormat(format);
  4858. if (internalFormat === gl.RGB) {
  4859. internalFormat = gl.RGBA;
  4860. }
  4861. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  4862. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4863. generateMipMaps = false;
  4864. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4865. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4866. }
  4867. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4868. generateMipMaps = false;
  4869. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4870. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  4871. }
  4872. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  4873. generateMipMaps = false;
  4874. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  4875. }
  4876. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  4877. generateMipMaps = false;
  4878. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  4879. }
  4880. var width = size;
  4881. var height = width;
  4882. texture.width = width;
  4883. texture.height = height;
  4884. // Double check on POT to generate Mips.
  4885. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4886. if (!isPot) {
  4887. generateMipMaps = false;
  4888. }
  4889. // Upload data if needed. The texture won't be ready until then.
  4890. if (data) {
  4891. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4892. }
  4893. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4894. // Filters
  4895. if (data && generateMipMaps) {
  4896. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4897. }
  4898. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4903. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4904. texture.generateMipMaps = generateMipMaps;
  4905. return texture;
  4906. }
  4907. /**
  4908. * Creates a new raw cube texture from a specified url
  4909. * @param url defines the url where the data is located
  4910. * @param scene defines the current scene
  4911. * @param size defines the size of the textures
  4912. * @param format defines the format of the data
  4913. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4914. * @param noMipmap defines if the engine should avoid generating the mip levels
  4915. * @param callback defines a callback used to extract texture data from loaded data
  4916. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  4917. * @param onLoad defines a callback called when texture is loaded
  4918. * @param onError defines a callback called if there is an error
  4919. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4920. * @param invertY defines if data must be stored with Y axis inverted
  4921. * @returns the cube texture as an InternalTexture
  4922. */
  4923. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  4924. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  4925. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  4926. onLoad: Nullable<() => void> = null,
  4927. onError: Nullable<(message?: string, exception?: any) => void> = null,
  4928. samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4929. invertY = false): InternalTexture {
  4930. var gl = this._gl;
  4931. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  4932. scene._addPendingData(texture);
  4933. texture.url = url;
  4934. this._internalTexturesCache.push(texture);
  4935. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  4936. scene._removePendingData(texture);
  4937. if (onError && request) {
  4938. onError(request.status + " " + request.statusText, exception);
  4939. }
  4940. };
  4941. var internalCallback = (data: any) => {
  4942. var width = texture.width;
  4943. var faceDataArrays = callback(data);
  4944. if (!faceDataArrays) {
  4945. return;
  4946. }
  4947. if (mipmapGenerator) {
  4948. var textureType = this._getWebGLTextureType(type);
  4949. var internalFormat = this._getInternalFormat(format);
  4950. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4951. var needConversion = false;
  4952. if (internalFormat === gl.RGB) {
  4953. internalFormat = gl.RGBA;
  4954. needConversion = true;
  4955. }
  4956. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4957. this._unpackFlipY(false);
  4958. var mipData = mipmapGenerator(faceDataArrays);
  4959. for (var level = 0; level < mipData.length; level++) {
  4960. var mipSize = width >> level;
  4961. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  4962. let mipFaceData = mipData[level][faceIndex];
  4963. if (needConversion) {
  4964. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  4965. }
  4966. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  4967. }
  4968. }
  4969. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4970. }
  4971. else {
  4972. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  4973. }
  4974. texture.isReady = true;
  4975. // this.resetTextureCache();
  4976. scene._removePendingData(texture);
  4977. if (onLoad) {
  4978. onLoad();
  4979. }
  4980. };
  4981. this._loadFile(url, data => {
  4982. internalCallback(data);
  4983. }, undefined, scene.database, true, onerror);
  4984. return texture;
  4985. };
  4986. /**
  4987. * Update a raw 3D texture
  4988. * @param texture defines the texture to update
  4989. * @param data defines the data to store
  4990. * @param format defines the data format
  4991. * @param invertY defines if data must be stored with Y axis inverted
  4992. * @param compression defines the used compression (can be null)
  4993. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  4994. */
  4995. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  4996. var internalType = this._getWebGLTextureType(textureType);
  4997. var internalFormat = this._getInternalFormat(format);
  4998. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  4999. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5000. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5001. if (!this._doNotHandleContextLost) {
  5002. texture._bufferView = data;
  5003. texture.format = format;
  5004. texture.invertY = invertY;
  5005. texture._compression = compression;
  5006. }
  5007. if (texture.width % 4 !== 0) {
  5008. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  5009. }
  5010. if (compression && data) {
  5011. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  5012. } else {
  5013. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  5014. }
  5015. if (texture.generateMipMaps) {
  5016. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5017. }
  5018. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5019. // this.resetTextureCache();
  5020. texture.isReady = true;
  5021. }
  5022. /**
  5023. * Creates a new raw 3D texture
  5024. * @param data defines the data used to create the texture
  5025. * @param width defines the width of the texture
  5026. * @param height defines the height of the texture
  5027. * @param depth defines the depth of the texture
  5028. * @param format defines the format of the texture
  5029. * @param generateMipMaps defines if the engine must generate mip levels
  5030. * @param invertY defines if data must be stored with Y axis inverted
  5031. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  5032. * @param compression defines the compressed used (can be null)
  5033. * @param textureType defines the compressed used (can be null)
  5034. * @returns a new raw 3D texture (stored in an InternalTexture)
  5035. */
  5036. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  5037. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  5038. texture.baseWidth = width;
  5039. texture.baseHeight = height;
  5040. texture.baseDepth = depth;
  5041. texture.width = width;
  5042. texture.height = height;
  5043. texture.depth = depth;
  5044. texture.format = format;
  5045. texture.type = textureType;
  5046. texture.generateMipMaps = generateMipMaps;
  5047. texture.samplingMode = samplingMode;
  5048. texture.is3D = true;
  5049. if (!this._doNotHandleContextLost) {
  5050. texture._bufferView = data;
  5051. }
  5052. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  5053. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5054. // Filters
  5055. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5056. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5057. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5058. if (generateMipMaps) {
  5059. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5060. }
  5061. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5062. this._internalTexturesCache.push(texture);
  5063. return texture;
  5064. }
  5065. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5066. var gl = this._gl;
  5067. if (!gl) {
  5068. return;
  5069. }
  5070. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  5071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5072. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5073. if (!noMipmap && !isCompressed) {
  5074. gl.generateMipmap(gl.TEXTURE_2D);
  5075. }
  5076. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5077. // this.resetTextureCache();
  5078. if (scene) {
  5079. scene._removePendingData(texture);
  5080. }
  5081. texture.onLoadedObservable.notifyObservers(texture);
  5082. texture.onLoadedObservable.clear();
  5083. }
  5084. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5085. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  5086. var maxTextureSize = this.getCaps().maxTextureSize;
  5087. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  5088. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  5089. var gl = this._gl;
  5090. if (!gl) {
  5091. return;
  5092. }
  5093. if (!texture._webGLTexture) {
  5094. // this.resetTextureCache();
  5095. if (scene) {
  5096. scene._removePendingData(texture);
  5097. }
  5098. return;
  5099. }
  5100. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5101. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5102. texture.baseWidth = width;
  5103. texture.baseHeight = height;
  5104. texture.width = potWidth;
  5105. texture.height = potHeight;
  5106. texture.isReady = true;
  5107. if (processFunction(potWidth, potHeight, () => {
  5108. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5109. })) {
  5110. // Returning as texture needs extra async steps
  5111. return;
  5112. }
  5113. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5114. }
  5115. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5116. // Create new RGBA data container.
  5117. var rgbaData: any;
  5118. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5119. rgbaData = new Float32Array(width * height * 4);
  5120. }
  5121. else {
  5122. rgbaData = new Uint32Array(width * height * 4);
  5123. }
  5124. // Convert each pixel.
  5125. for (let x = 0; x < width; x++) {
  5126. for (let y = 0; y < height; y++) {
  5127. let index = (y * width + x) * 3;
  5128. let newIndex = (y * width + x) * 4;
  5129. // Map Old Value to new value.
  5130. rgbaData[newIndex + 0] = rgbData[index + 0];
  5131. rgbaData[newIndex + 1] = rgbData[index + 1];
  5132. rgbaData[newIndex + 2] = rgbData[index + 2];
  5133. // Add fully opaque alpha channel.
  5134. rgbaData[newIndex + 3] = 1;
  5135. }
  5136. }
  5137. return rgbaData;
  5138. }
  5139. /** @hidden */
  5140. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5141. var gl = this._gl;
  5142. if (texture._framebuffer) {
  5143. gl.deleteFramebuffer(texture._framebuffer);
  5144. texture._framebuffer = null;
  5145. }
  5146. if (texture._depthStencilBuffer) {
  5147. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5148. texture._depthStencilBuffer = null;
  5149. }
  5150. if (texture._MSAAFramebuffer) {
  5151. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5152. texture._MSAAFramebuffer = null;
  5153. }
  5154. if (texture._MSAARenderBuffer) {
  5155. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5156. texture._MSAARenderBuffer = null;
  5157. }
  5158. }
  5159. /** @hidden */
  5160. public _releaseTexture(texture: InternalTexture): void {
  5161. var gl = this._gl;
  5162. this._releaseFramebufferObjects(texture);
  5163. gl.deleteTexture(texture._webGLTexture);
  5164. // Unbind channels
  5165. this.unbindAllTextures();
  5166. var index = this._internalTexturesCache.indexOf(texture);
  5167. if (index !== -1) {
  5168. this._internalTexturesCache.splice(index, 1);
  5169. }
  5170. // Integrated fixed lod samplers.
  5171. if (texture._lodTextureHigh) {
  5172. texture._lodTextureHigh.dispose();
  5173. }
  5174. if (texture._lodTextureMid) {
  5175. texture._lodTextureMid.dispose();
  5176. }
  5177. if (texture._lodTextureLow) {
  5178. texture._lodTextureLow.dispose();
  5179. }
  5180. // Set output texture of post process to null if the texture has been released/disposed
  5181. this.scenes.forEach((scene)=>{
  5182. scene.postProcesses.forEach((postProcess)=>{
  5183. if(postProcess._outputTexture == texture){
  5184. postProcess._outputTexture = null;
  5185. }
  5186. });
  5187. scene.cameras.forEach((camera)=>{
  5188. camera._postProcesses.forEach((postProcess)=>{
  5189. if(postProcess){
  5190. if(postProcess._outputTexture == texture){
  5191. postProcess._outputTexture = null;
  5192. }
  5193. }
  5194. });
  5195. });
  5196. })
  5197. }
  5198. private setProgram(program: WebGLProgram): void {
  5199. if (this._currentProgram !== program) {
  5200. this._gl.useProgram(program);
  5201. this._currentProgram = program;
  5202. }
  5203. }
  5204. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5205. /**
  5206. * Binds an effect to the webGL context
  5207. * @param effect defines the effect to bind
  5208. */
  5209. public bindSamplers(effect: Effect): void {
  5210. this.setProgram(effect.getProgram());
  5211. var samplers = effect.getSamplers();
  5212. for (var index = 0; index < samplers.length; index++) {
  5213. var uniform = effect.getUniform(samplers[index]);
  5214. if (uniform) {
  5215. this._boundUniforms[index] = uniform;
  5216. }
  5217. }
  5218. this._currentEffect = null;
  5219. }
  5220. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5221. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5222. return;
  5223. }
  5224. // Remove
  5225. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5226. // Bind last to it
  5227. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5228. // Bind to dummy
  5229. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5230. }
  5231. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5232. if (!internalTexture) {
  5233. return -1;
  5234. }
  5235. internalTexture._initialSlot = channel;
  5236. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5237. if (channel !== internalTexture._designatedSlot) {
  5238. this._textureCollisions.addCount(1, false);
  5239. }
  5240. } else {
  5241. if (channel !== internalTexture._designatedSlot) {
  5242. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5243. return internalTexture._designatedSlot;
  5244. } else {
  5245. // No slot for this texture, let's pick a new one (if we find a free slot)
  5246. if (this._nextFreeTextureSlots.length) {
  5247. return this._nextFreeTextureSlots[0];
  5248. }
  5249. // We need to recycle the oldest bound texture, sorry.
  5250. this._textureCollisions.addCount(1, false);
  5251. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5252. }
  5253. }
  5254. }
  5255. return channel;
  5256. }
  5257. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5258. previous!.next = next;
  5259. next!.previous = previous;
  5260. }
  5261. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5262. let currentSlot = internalTexture._designatedSlot;
  5263. if (currentSlot === -1) {
  5264. return -1;
  5265. }
  5266. internalTexture._designatedSlot = -1;
  5267. if (this.disableTextureBindingOptimization) {
  5268. return -1;
  5269. }
  5270. // Remove from bound list
  5271. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5272. // Free the slot
  5273. this._boundTexturesCache[currentSlot] = null;
  5274. this._nextFreeTextureSlots.push(currentSlot);
  5275. return currentSlot;
  5276. }
  5277. private _activateCurrentTexture() {
  5278. if (this._currentTextureChannel !== this._activeChannel) {
  5279. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5280. this._currentTextureChannel = this._activeChannel;
  5281. }
  5282. }
  5283. /** @hidden */
  5284. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  5285. var wasPreviouslyBound = false;
  5286. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5287. this._activeChannel = texture._designatedSlot;
  5288. }
  5289. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5290. let isTextureForRendering = texture && texture._initialSlot > -1;
  5291. if (currentTextureBound !== texture || force) {
  5292. if (currentTextureBound) {
  5293. this._removeDesignatedSlot(currentTextureBound);
  5294. }
  5295. this._activateCurrentTexture();
  5296. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5297. this._boundTexturesCache[this._activeChannel] = texture;
  5298. if (texture) {
  5299. if (!this.disableTextureBindingOptimization) {
  5300. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5301. if (slotIndex > -1) {
  5302. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5303. }
  5304. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5305. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5306. }
  5307. texture._designatedSlot = this._activeChannel;
  5308. }
  5309. } else if (forTextureDataUpdate) {
  5310. wasPreviouslyBound = true;
  5311. this._activateCurrentTexture();
  5312. }
  5313. if (isTextureForRendering && !forTextureDataUpdate) {
  5314. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5315. }
  5316. return wasPreviouslyBound;
  5317. }
  5318. /** @hidden */
  5319. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5320. if (channel < 0) {
  5321. return;
  5322. }
  5323. if (texture) {
  5324. channel = this._getCorrectTextureChannel(channel, texture);
  5325. }
  5326. this._activeChannel = channel;
  5327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5328. }
  5329. /**
  5330. * Sets a texture to the webGL context from a postprocess
  5331. * @param channel defines the channel to use
  5332. * @param postProcess defines the source postprocess
  5333. */
  5334. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5335. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5336. }
  5337. /**
  5338. * Binds the output of the passed in post process to the texture channel specified
  5339. * @param channel The channel the texture should be bound to
  5340. * @param postProcess The post process which's output should be bound
  5341. */
  5342. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5343. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5344. }
  5345. /**
  5346. * Unbind all textures from the webGL context
  5347. */
  5348. public unbindAllTextures(): void {
  5349. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5350. this._activeChannel = channel;
  5351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5353. if (this.webGLVersion > 1) {
  5354. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5355. }
  5356. }
  5357. }
  5358. /**
  5359. * Sets a texture to the according uniform.
  5360. * @param channel The texture channel
  5361. * @param uniform The uniform to set
  5362. * @param texture The texture to apply
  5363. */
  5364. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5365. if (channel < 0) {
  5366. return;
  5367. }
  5368. if (uniform) {
  5369. this._boundUniforms[channel] = uniform;
  5370. }
  5371. this._setTexture(channel, texture);
  5372. }
  5373. /**
  5374. * Sets a depth stencil texture from a render target to the according uniform.
  5375. * @param channel The texture channel
  5376. * @param uniform The uniform to set
  5377. * @param texture The render target texture containing the depth stencil texture to apply
  5378. */
  5379. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5380. if (channel < 0) {
  5381. return;
  5382. }
  5383. if (uniform) {
  5384. this._boundUniforms[channel] = uniform;
  5385. }
  5386. if (!texture || !texture.depthStencilTexture) {
  5387. this._setTexture(channel, null);
  5388. }
  5389. else {
  5390. this._setTexture(channel, texture, false, true);
  5391. }
  5392. }
  5393. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5394. let uniform = this._boundUniforms[sourceSlot];
  5395. if (uniform._currentState === destination) {
  5396. return;
  5397. }
  5398. this._gl.uniform1i(uniform, destination);
  5399. uniform._currentState = destination;
  5400. }
  5401. private _getTextureWrapMode(mode: number): number {
  5402. switch(mode) {
  5403. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  5404. return this._gl.REPEAT;
  5405. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  5406. return this._gl.CLAMP_TO_EDGE;
  5407. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  5408. return this._gl.MIRRORED_REPEAT;
  5409. }
  5410. return this._gl.REPEAT;
  5411. }
  5412. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5413. // Not ready?
  5414. if (!texture) {
  5415. if (this._boundTexturesCache[channel] != null) {
  5416. this._activeChannel = channel;
  5417. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5418. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5419. if (this.webGLVersion > 1) {
  5420. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5421. }
  5422. }
  5423. return false;
  5424. }
  5425. // Video
  5426. if ((<VideoTexture>texture).video) {
  5427. this._activeChannel = channel;
  5428. (<VideoTexture>texture).update();
  5429. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5430. texture.delayLoad();
  5431. return false;
  5432. }
  5433. let internalTexture: InternalTexture;
  5434. if (depthStencilTexture) {
  5435. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5436. }
  5437. else if (texture.isReady()) {
  5438. internalTexture = <InternalTexture>texture.getInternalTexture();
  5439. }
  5440. else if (texture.isCube) {
  5441. internalTexture = this.emptyCubeTexture;
  5442. }
  5443. else if (texture.is3D) {
  5444. internalTexture = this.emptyTexture3D;
  5445. }
  5446. else {
  5447. internalTexture = this.emptyTexture;
  5448. }
  5449. if (!isPartOfTextureArray) {
  5450. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5451. }
  5452. let needToBind = true;
  5453. if (this._boundTexturesCache[channel] === internalTexture) {
  5454. this._moveBoundTextureOnTop(internalTexture);
  5455. if (!isPartOfTextureArray) {
  5456. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5457. }
  5458. needToBind = false;
  5459. }
  5460. this._activeChannel = channel;
  5461. if (internalTexture && internalTexture.is3D) {
  5462. if (needToBind) {
  5463. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5464. }
  5465. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5466. internalTexture._cachedWrapU = texture.wrapU;
  5467. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5468. }
  5469. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5470. internalTexture._cachedWrapV = texture.wrapV;
  5471. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5472. }
  5473. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5474. internalTexture._cachedWrapR = texture.wrapR;
  5475. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5476. }
  5477. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5478. }
  5479. else if (internalTexture && internalTexture.isCube) {
  5480. if (needToBind) {
  5481. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5482. }
  5483. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5484. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5485. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5486. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5487. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5488. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5489. }
  5490. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5491. } else {
  5492. if (needToBind) {
  5493. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5494. }
  5495. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5496. internalTexture._cachedWrapU = texture.wrapU;
  5497. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5498. }
  5499. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5500. internalTexture._cachedWrapV = texture.wrapV;
  5501. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5502. }
  5503. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5504. }
  5505. return true;
  5506. }
  5507. /**
  5508. * Sets an array of texture to the webGL context
  5509. * @param channel defines the channel where the texture array must be set
  5510. * @param uniform defines the associated uniform location
  5511. * @param textures defines the array of textures to bind
  5512. */
  5513. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5514. if (channel < 0 || !uniform) {
  5515. return;
  5516. }
  5517. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5518. this._textureUnits = new Int32Array(textures.length);
  5519. }
  5520. for (let i = 0; i < textures.length; i++) {
  5521. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5522. }
  5523. this._gl.uniform1iv(uniform, this._textureUnits);
  5524. for (var index = 0; index < textures.length; index++) {
  5525. this._setTexture(this._textureUnits[index], textures[index], true);
  5526. }
  5527. }
  5528. /** @hidden */
  5529. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5530. var internalTexture = texture.getInternalTexture();
  5531. if (!internalTexture) {
  5532. return;
  5533. }
  5534. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5535. var value = texture.anisotropicFilteringLevel;
  5536. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  5537. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  5538. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  5539. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5540. }
  5541. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5542. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5543. internalTexture._cachedAnisotropicFilteringLevel = value;
  5544. }
  5545. }
  5546. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5547. this._bindTextureDirectly(target, texture, true, true);
  5548. this._gl.texParameterf(target, parameter, value);
  5549. }
  5550. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5551. if (texture) {
  5552. this._bindTextureDirectly(target, texture, true, true);
  5553. }
  5554. this._gl.texParameteri(target, parameter, value);
  5555. }
  5556. /**
  5557. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5558. * @param x defines the x coordinate of the rectangle where pixels must be read
  5559. * @param y defines the y coordinate of the rectangle where pixels must be read
  5560. * @param width defines the width of the rectangle where pixels must be read
  5561. * @param height defines the height of the rectangle where pixels must be read
  5562. * @returns a Uint8Array containing RGBA colors
  5563. */
  5564. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5565. var data = new Uint8Array(height * width * 4);
  5566. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5567. return data;
  5568. }
  5569. /**
  5570. * Add an externaly attached data from its key.
  5571. * This method call will fail and return false, if such key already exists.
  5572. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5573. * @param key the unique key that identifies the data
  5574. * @param data the data object to associate to the key for this Engine instance
  5575. * @return true if no such key were already present and the data was added successfully, false otherwise
  5576. */
  5577. public addExternalData<T>(key: string, data: T): boolean {
  5578. if (!this._externalData) {
  5579. this._externalData = new StringDictionary<Object>();
  5580. }
  5581. return this._externalData.add(key, data);
  5582. }
  5583. /**
  5584. * Get an externaly attached data from its key
  5585. * @param key the unique key that identifies the data
  5586. * @return the associated data, if present (can be null), or undefined if not present
  5587. */
  5588. public getExternalData<T>(key: string): T {
  5589. if (!this._externalData) {
  5590. this._externalData = new StringDictionary<Object>();
  5591. }
  5592. return <T>this._externalData.get(key);
  5593. }
  5594. /**
  5595. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5596. * @param key the unique key that identifies the data
  5597. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5598. * @return the associated data, can be null if the factory returned null.
  5599. */
  5600. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5601. if (!this._externalData) {
  5602. this._externalData = new StringDictionary<Object>();
  5603. }
  5604. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5605. }
  5606. /**
  5607. * Remove an externaly attached data from the Engine instance
  5608. * @param key the unique key that identifies the data
  5609. * @return true if the data was successfully removed, false if it doesn't exist
  5610. */
  5611. public removeExternalData(key: string): boolean {
  5612. if (!this._externalData) {
  5613. this._externalData = new StringDictionary<Object>();
  5614. }
  5615. return this._externalData.remove(key);
  5616. }
  5617. /**
  5618. * Unbind all vertex attributes from the webGL context
  5619. */
  5620. public unbindAllAttributes() {
  5621. if (this._mustWipeVertexAttributes) {
  5622. this._mustWipeVertexAttributes = false;
  5623. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5624. this._gl.disableVertexAttribArray(i);
  5625. this._vertexAttribArraysEnabled[i] = false;
  5626. this._currentBufferPointers[i].active = false;
  5627. }
  5628. return;
  5629. }
  5630. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5631. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5632. continue;
  5633. }
  5634. this._gl.disableVertexAttribArray(i);
  5635. this._vertexAttribArraysEnabled[i] = false;
  5636. this._currentBufferPointers[i].active = false;
  5637. }
  5638. }
  5639. /**
  5640. * 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
  5641. */
  5642. public releaseEffects() {
  5643. for (var name in this._compiledEffects) {
  5644. this._deleteProgram(this._compiledEffects[name]._program)
  5645. }
  5646. this._compiledEffects = {};
  5647. }
  5648. /**
  5649. * Dispose and release all associated resources
  5650. */
  5651. public dispose(): void {
  5652. this.hideLoadingUI();
  5653. this.stopRenderLoop();
  5654. // Release postProcesses
  5655. while (this.postProcesses.length) {
  5656. this.postProcesses[0].dispose();
  5657. }
  5658. // Empty texture
  5659. if (this._emptyTexture) {
  5660. this._releaseTexture(this._emptyTexture);
  5661. this._emptyTexture = null;
  5662. }
  5663. if (this._emptyCubeTexture) {
  5664. this._releaseTexture(this._emptyCubeTexture);
  5665. this._emptyCubeTexture = null;
  5666. }
  5667. // Rescale PP
  5668. if (this._rescalePostProcess) {
  5669. this._rescalePostProcess.dispose();
  5670. }
  5671. // Release scenes
  5672. while (this.scenes.length) {
  5673. this.scenes[0].dispose();
  5674. }
  5675. // Release audio engine
  5676. if (Engine.audioEngine) {
  5677. Engine.audioEngine.dispose();
  5678. }
  5679. // Release effects
  5680. this.releaseEffects();
  5681. // Unbind
  5682. this.unbindAllAttributes();
  5683. this._boundUniforms = [];
  5684. if (this._dummyFramebuffer) {
  5685. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5686. }
  5687. //WebVR
  5688. this.disableVR();
  5689. // Events
  5690. if (Tools.IsWindowObjectExist()) {
  5691. window.removeEventListener("blur", this._onBlur);
  5692. window.removeEventListener("focus", this._onFocus);
  5693. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5694. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5695. if (this._renderingCanvas) {
  5696. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5697. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5698. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5699. if (!this._doNotHandleContextLost) {
  5700. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5701. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5702. }
  5703. }
  5704. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5705. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5706. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5707. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5708. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5709. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5710. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5711. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5712. if (this._onVrDisplayConnect) {
  5713. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5714. if (this._onVrDisplayDisconnect) {
  5715. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5716. }
  5717. if (this._onVrDisplayPresentChange) {
  5718. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5719. }
  5720. this._onVrDisplayConnect = null;
  5721. this._onVrDisplayDisconnect = null;
  5722. }
  5723. }
  5724. // Remove from Instances
  5725. var index = Engine.Instances.indexOf(this);
  5726. if (index >= 0) {
  5727. Engine.Instances.splice(index, 1);
  5728. }
  5729. this._workingCanvas = null;
  5730. this._workingContext = null;
  5731. this._currentBufferPointers = [];
  5732. this._renderingCanvas = null;
  5733. this._currentProgram = null;
  5734. this._bindedRenderFunction = null;
  5735. this.onResizeObservable.clear();
  5736. this.onCanvasBlurObservable.clear();
  5737. this.onCanvasFocusObservable.clear();
  5738. this.onCanvasPointerOutObservable.clear();
  5739. this.onBeginFrameObservable.clear();
  5740. this.onEndFrameObservable.clear();
  5741. Effect.ResetCache();
  5742. // Abort active requests
  5743. for (let request of this._activeRequests) {
  5744. request.abort();
  5745. }
  5746. }
  5747. // Loading screen
  5748. /**
  5749. * Display the loading screen
  5750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5751. */
  5752. public displayLoadingUI(): void {
  5753. if (!Tools.IsWindowObjectExist()) {
  5754. return;
  5755. }
  5756. const loadingScreen = this.loadingScreen;
  5757. if (loadingScreen) {
  5758. loadingScreen.displayLoadingUI();
  5759. }
  5760. }
  5761. /**
  5762. * Hide the loading screen
  5763. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5764. */
  5765. public hideLoadingUI(): void {
  5766. if (!Tools.IsWindowObjectExist()) {
  5767. return;
  5768. }
  5769. const loadingScreen = this.loadingScreen;
  5770. if (loadingScreen) {
  5771. loadingScreen.hideLoadingUI();
  5772. }
  5773. }
  5774. /**
  5775. * Gets the current loading screen object
  5776. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5777. */
  5778. public get loadingScreen(): ILoadingScreen {
  5779. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  5780. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  5781. return this._loadingScreen;
  5782. }
  5783. /**
  5784. * Sets the current loading screen object
  5785. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5786. */
  5787. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5788. this._loadingScreen = loadingScreen;
  5789. }
  5790. /**
  5791. * Sets the current loading screen text
  5792. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5793. */
  5794. public set loadingUIText(text: string) {
  5795. this.loadingScreen.loadingUIText = text;
  5796. }
  5797. /**
  5798. * Sets the current loading screen background color
  5799. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5800. */
  5801. public set loadingUIBackgroundColor(color: string) {
  5802. this.loadingScreen.loadingUIBackgroundColor = color;
  5803. }
  5804. /**
  5805. * Attach a new callback raised when context lost event is fired
  5806. * @param callback defines the callback to call
  5807. */
  5808. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5809. if (this._renderingCanvas) {
  5810. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5811. }
  5812. }
  5813. /**
  5814. * Attach a new callback raised when context restored event is fired
  5815. * @param callback defines the callback to call
  5816. */
  5817. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5818. if (this._renderingCanvas) {
  5819. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5820. }
  5821. }
  5822. /**
  5823. * Gets the source code of the vertex shader associated with a specific webGL program
  5824. * @param program defines the program to use
  5825. * @returns a string containing the source code of the vertex shader associated with the program
  5826. */
  5827. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5828. var shaders = this._gl.getAttachedShaders(program);
  5829. if (!shaders) {
  5830. return null;
  5831. }
  5832. return this._gl.getShaderSource(shaders[0]);
  5833. }
  5834. /**
  5835. * Gets the source code of the fragment shader associated with a specific webGL program
  5836. * @param program defines the program to use
  5837. * @returns a string containing the source code of the fragment shader associated with the program
  5838. */
  5839. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5840. var shaders = this._gl.getAttachedShaders(program);
  5841. if (!shaders) {
  5842. return null;
  5843. }
  5844. return this._gl.getShaderSource(shaders[1]);
  5845. }
  5846. /**
  5847. * Get the current error code of the webGL context
  5848. * @returns the error code
  5849. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5850. */
  5851. public getError(): number {
  5852. return this._gl.getError();
  5853. }
  5854. // FPS
  5855. /**
  5856. * Gets the current framerate
  5857. * @returns a number representing the framerate
  5858. */
  5859. public getFps(): number {
  5860. return this._fps;
  5861. }
  5862. /**
  5863. * Gets the time spent between current and previous frame
  5864. * @returns a number representing the delta time in ms
  5865. */
  5866. public getDeltaTime(): number {
  5867. return this._deltaTime;
  5868. }
  5869. private _measureFps(): void {
  5870. this._performanceMonitor.sampleFrame();
  5871. this._fps = this._performanceMonitor.averageFPS;
  5872. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5873. }
  5874. /** @hidden */
  5875. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0): ArrayBufferView {
  5876. let gl = this._gl;
  5877. if (!this._dummyFramebuffer) {
  5878. let dummy = gl.createFramebuffer();
  5879. if (!dummy) {
  5880. throw new Error("Unable to create dummy framebuffer");
  5881. }
  5882. this._dummyFramebuffer = dummy;
  5883. }
  5884. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5885. if (faceIndex > -1) {
  5886. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  5887. } else {
  5888. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  5889. }
  5890. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5891. let buffer: ArrayBufferView;
  5892. switch (readType) {
  5893. case gl.UNSIGNED_BYTE:
  5894. buffer = new Uint8Array(4 * width * height);
  5895. readType = gl.UNSIGNED_BYTE;
  5896. break;
  5897. default:
  5898. buffer = new Float32Array(4 * width * height);
  5899. readType = gl.FLOAT;
  5900. break;
  5901. }
  5902. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  5903. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  5904. return buffer;
  5905. }
  5906. private _canRenderToFloatFramebuffer(): boolean {
  5907. if (this._webGLVersion > 1) {
  5908. return this._caps.colorBufferFloat;
  5909. }
  5910. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  5911. }
  5912. private _canRenderToHalfFloatFramebuffer(): boolean {
  5913. if (this._webGLVersion > 1) {
  5914. return this._caps.colorBufferFloat;
  5915. }
  5916. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  5917. }
  5918. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  5919. private _canRenderToFramebuffer(type: number): boolean {
  5920. let gl = this._gl;
  5921. //clear existing errors
  5922. while (gl.getError() !== gl.NO_ERROR) { }
  5923. let successful = true;
  5924. let texture = gl.createTexture();
  5925. gl.bindTexture(gl.TEXTURE_2D, texture);
  5926. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  5927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5929. let fb = gl.createFramebuffer();
  5930. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  5931. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5932. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  5933. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  5934. successful = successful && (gl.getError() === gl.NO_ERROR);
  5935. //try render by clearing frame buffer's color buffer
  5936. if (successful) {
  5937. gl.clear(gl.COLOR_BUFFER_BIT);
  5938. successful = successful && (gl.getError() === gl.NO_ERROR);
  5939. }
  5940. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  5941. if (successful) {
  5942. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  5943. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5944. let readFormat = gl.RGBA;
  5945. let readType = gl.UNSIGNED_BYTE;
  5946. let buffer = new Uint8Array(4);
  5947. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  5948. successful = successful && (gl.getError() === gl.NO_ERROR);
  5949. }
  5950. //clean up
  5951. gl.deleteTexture(texture);
  5952. gl.deleteFramebuffer(fb);
  5953. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5954. //clear accumulated errors
  5955. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  5956. return successful;
  5957. }
  5958. /** @hidden */
  5959. public _getWebGLTextureType(type: number): number {
  5960. if (this._webGLVersion === 1) {
  5961. switch (type) {
  5962. case Engine.TEXTURETYPE_FLOAT:
  5963. return this._gl.FLOAT;
  5964. case Engine.TEXTURETYPE_HALF_FLOAT:
  5965. return this._gl.HALF_FLOAT_OES;
  5966. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  5967. return this._gl.UNSIGNED_BYTE;
  5968. }
  5969. return this._gl.UNSIGNED_BYTE;
  5970. }
  5971. switch (type) {
  5972. case Engine.TEXTURETYPE_BYTE:
  5973. return this._gl.BYTE;
  5974. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  5975. return this._gl.UNSIGNED_BYTE;
  5976. case Engine.TEXTURETYPE_SHORT:
  5977. return this._gl.SHORT;
  5978. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  5979. return this._gl.UNSIGNED_SHORT;
  5980. case Engine.TEXTURETYPE_INT:
  5981. return this._gl.INT;
  5982. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  5983. return this._gl.UNSIGNED_INT;
  5984. case Engine.TEXTURETYPE_FLOAT:
  5985. return this._gl.FLOAT;
  5986. case Engine.TEXTURETYPE_HALF_FLOAT:
  5987. return this._gl.HALF_FLOAT;
  5988. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  5989. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  5990. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  5991. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  5992. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  5993. return this._gl.UNSIGNED_SHORT_5_6_5;
  5994. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  5995. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  5996. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  5997. return this._gl.UNSIGNED_INT_24_8;
  5998. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  5999. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  6000. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6001. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  6002. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  6003. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  6004. }
  6005. return this._gl.UNSIGNED_BYTE;
  6006. };
  6007. private _getInternalFormat(format: number): number {
  6008. var internalFormat = this._gl.RGBA;
  6009. switch (format) {
  6010. case Engine.TEXTUREFORMAT_ALPHA:
  6011. internalFormat = this._gl.ALPHA;
  6012. break;
  6013. case Engine.TEXTUREFORMAT_LUMINANCE:
  6014. internalFormat = this._gl.LUMINANCE;
  6015. break;
  6016. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6017. internalFormat = this._gl.LUMINANCE_ALPHA;
  6018. break;
  6019. case Engine.TEXTUREFORMAT_RED:
  6020. internalFormat = this._gl.RED;
  6021. break;
  6022. case Engine.TEXTUREFORMAT_RG:
  6023. internalFormat = this._gl.RG;
  6024. break;
  6025. case Engine.TEXTUREFORMAT_RGB:
  6026. internalFormat = this._gl.RGB;
  6027. break;
  6028. case Engine.TEXTUREFORMAT_RGBA:
  6029. internalFormat = this._gl.RGBA;
  6030. break;
  6031. }
  6032. if (this._webGLVersion > 1) {
  6033. switch (format) {
  6034. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6035. internalFormat = this._gl.RED_INTEGER;
  6036. break;
  6037. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6038. internalFormat = this._gl.RG_INTEGER;
  6039. break;
  6040. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6041. internalFormat = this._gl.RGB_INTEGER;
  6042. break;
  6043. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6044. internalFormat = this._gl.RGBA_INTEGER;
  6045. break;
  6046. }
  6047. }
  6048. return internalFormat;
  6049. }
  6050. /** @hidden */
  6051. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  6052. if (this._webGLVersion === 1) {
  6053. if (format !== undefined) {
  6054. switch(format) {
  6055. case Engine.TEXTUREFORMAT_ALPHA:
  6056. return this._gl.ALPHA;
  6057. case Engine.TEXTUREFORMAT_LUMINANCE:
  6058. return this._gl.LUMINANCE;
  6059. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6060. return this._gl.LUMINANCE_ALPHA;
  6061. }
  6062. }
  6063. return this._gl.RGBA;
  6064. }
  6065. switch (type) {
  6066. case Engine.TEXTURETYPE_BYTE:
  6067. switch (format) {
  6068. case Engine.TEXTUREFORMAT_RED:
  6069. return this._gl.R8_SNORM;
  6070. case Engine.TEXTUREFORMAT_RG:
  6071. return this._gl.RG8_SNORM;
  6072. case Engine.TEXTUREFORMAT_RGB:
  6073. return this._gl.RGB8_SNORM;
  6074. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6075. return this._gl.R8I;
  6076. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6077. return this._gl.RG8I;
  6078. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6079. return this._gl.RGB8I;
  6080. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6081. return this._gl.RGBA8I;
  6082. default:
  6083. return this._gl.RGBA8_SNORM;
  6084. }
  6085. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6086. switch (format) {
  6087. case Engine.TEXTUREFORMAT_RED:
  6088. return this._gl.R8;
  6089. case Engine.TEXTUREFORMAT_RG:
  6090. return this._gl.RG8;
  6091. case Engine.TEXTUREFORMAT_RGB:
  6092. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  6093. case Engine.TEXTUREFORMAT_RGBA:
  6094. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  6095. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6096. return this._gl.R8UI;
  6097. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6098. return this._gl.RG8UI;
  6099. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6100. return this._gl.RGB8UI;
  6101. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6102. return this._gl.RGBA8UI;
  6103. default:
  6104. return this._gl.RGBA8;
  6105. }
  6106. case Engine.TEXTURETYPE_SHORT:
  6107. switch (format) {
  6108. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6109. return this._gl.R16I;
  6110. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6111. return this._gl.RG16I;
  6112. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6113. return this._gl.RGB16I;
  6114. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6115. return this._gl.RGBA16I;
  6116. default:
  6117. return this._gl.RGBA16I;
  6118. }
  6119. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6120. switch (format) {
  6121. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6122. return this._gl.R16UI;
  6123. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6124. return this._gl.RG16UI;
  6125. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6126. return this._gl.RGB16UI;
  6127. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6128. return this._gl.RGBA16UI;
  6129. default:
  6130. return this._gl.RGBA16UI;
  6131. }
  6132. case Engine.TEXTURETYPE_INT:
  6133. switch (format) {
  6134. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6135. return this._gl.R32I;
  6136. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6137. return this._gl.RG32I;
  6138. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6139. return this._gl.RGB32I;
  6140. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6141. return this._gl.RGBA32I;
  6142. default:
  6143. return this._gl.RGBA32I;
  6144. }
  6145. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6146. switch (format) {
  6147. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6148. return this._gl.R32UI;
  6149. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6150. return this._gl.RG32UI;
  6151. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6152. return this._gl.RGB32UI;
  6153. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6154. return this._gl.RGBA32UI;
  6155. default:
  6156. return this._gl.RGBA32UI;
  6157. }
  6158. case Engine.TEXTURETYPE_FLOAT:
  6159. switch (format) {
  6160. case Engine.TEXTUREFORMAT_RED:
  6161. return this._gl.R32F; // By default. Other possibility is R16F.
  6162. case Engine.TEXTUREFORMAT_RG:
  6163. return this._gl.RG32F; // By default. Other possibility is RG16F.
  6164. case Engine.TEXTUREFORMAT_RGB:
  6165. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  6166. case Engine.TEXTUREFORMAT_RGBA:
  6167. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  6168. default:
  6169. return this._gl.RGBA32F;
  6170. }
  6171. case Engine.TEXTURETYPE_HALF_FLOAT:
  6172. switch (format) {
  6173. case Engine.TEXTUREFORMAT_RED:
  6174. return this._gl.R16F;
  6175. case Engine.TEXTUREFORMAT_RG:
  6176. return this._gl.RG16F;
  6177. case Engine.TEXTUREFORMAT_RGB:
  6178. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  6179. case Engine.TEXTUREFORMAT_RGBA:
  6180. return this._gl.RGBA16F;
  6181. default:
  6182. return this._gl.RGBA16F;
  6183. }
  6184. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6185. return this._gl.RGB565;
  6186. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6187. return this._gl.R11F_G11F_B10F;
  6188. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6189. return this._gl.RGB9_E5;
  6190. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6191. return this._gl.RGBA4;
  6192. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6193. return this._gl.RGB5_A1;
  6194. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6195. switch (format) {
  6196. case Engine.TEXTUREFORMAT_RGBA:
  6197. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  6198. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6199. return this._gl.RGB10_A2UI;
  6200. default:
  6201. return this._gl.RGB10_A2;
  6202. }
  6203. }
  6204. return this._gl.RGBA8;
  6205. };
  6206. /** @hidden */
  6207. public _getRGBAMultiSampleBufferFormat(type: number): number {
  6208. if (type === Engine.TEXTURETYPE_FLOAT) {
  6209. return this._gl.RGBA32F;
  6210. }
  6211. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6212. return this._gl.RGBA16F;
  6213. }
  6214. return this._gl.RGBA8;
  6215. };
  6216. /** @hidden */
  6217. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6218. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  6219. this._activeRequests.push(request);
  6220. request.onCompleteObservable.add(request => {
  6221. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6222. });
  6223. return request;
  6224. }
  6225. /** @hidden */
  6226. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6227. return new Promise((resolve, reject) => {
  6228. this._loadFile(url, (data) => {
  6229. resolve(data);
  6230. }, undefined, database, useArrayBuffer, (request, exception) => {
  6231. reject(exception);
  6232. })
  6233. });
  6234. }
  6235. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6236. var onload = (data: string | ArrayBuffer) => {
  6237. loadedFiles[index] = data;
  6238. (<any>loadedFiles)._internalCount++;
  6239. if ((<any>loadedFiles)._internalCount === 6) {
  6240. onfinish(loadedFiles);
  6241. }
  6242. };
  6243. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6244. if (onErrorCallBack && request) {
  6245. onErrorCallBack(request.status + " " + request.statusText, exception);
  6246. }
  6247. };
  6248. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6249. }
  6250. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6251. var loadedFiles: (string | ArrayBuffer)[] = [];
  6252. (<any>loadedFiles)._internalCount = 0;
  6253. for (let index = 0; index < 6; index++) {
  6254. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6255. }
  6256. }
  6257. // Statics
  6258. /**
  6259. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6260. * @returns true if the engine can be created
  6261. * @ignorenaming
  6262. */
  6263. public static isSupported(): boolean {
  6264. try {
  6265. var tempcanvas = document.createElement("canvas");
  6266. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6267. return gl != null && !!window.WebGLRenderingContext;
  6268. } catch (e) {
  6269. return false;
  6270. }
  6271. }
  6272. }
  6273. }