babylon.engine.ts 326 KB

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