babylon.engine.ts 261 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196
  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. export class InstancingAttributeInfo {
  155. /**
  156. * Index/offset of the attribute in the vertex shader
  157. */
  158. index: number;
  159. /**
  160. * size of the attribute, 1, 2, 3 or 4
  161. */
  162. attributeSize: number;
  163. /**
  164. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  165. * default is FLOAT
  166. */
  167. attribyteType: number;
  168. /**
  169. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  170. */
  171. normalized: boolean;
  172. /**
  173. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  174. */
  175. offset: number;
  176. /**
  177. * Name of the GLSL attribute, for debugging purpose only
  178. */
  179. attributeName: string;
  180. }
  181. /**
  182. * Define options used to create a render target texture
  183. */
  184. export class RenderTargetCreationOptions {
  185. generateMipMaps?: boolean;
  186. generateDepthBuffer?: boolean;
  187. generateStencilBuffer?: boolean;
  188. type?: number;
  189. samplingMode?: number;
  190. }
  191. /**
  192. * Define options used to create a depth texture
  193. */
  194. export class DepthTextureCreationOptions {
  195. /** Specifies whether or not a stencil should be allocated in the texture */
  196. generateStencil?: boolean;
  197. /** Specifies whether or not bilinear filtering is enable on the texture */
  198. bilinearFiltering?: boolean;
  199. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  200. comparisonFunction?: number;
  201. /** Specifies if the created texture is a cube texture */
  202. isCube?: boolean;
  203. }
  204. /**
  205. * Regroup several parameters relative to the browser in use
  206. */
  207. export class EngineCapabilities {
  208. /** The maximum textures image */
  209. public maxTexturesImageUnits: number;
  210. public maxVertexTextureImageUnits: number;
  211. public maxCombinedTexturesImageUnits: number;
  212. /** The maximum texture size */
  213. public maxTextureSize: number;
  214. public maxCubemapTextureSize: number;
  215. public maxRenderTextureSize: number;
  216. public maxVertexAttribs: number;
  217. public maxVaryingVectors: number;
  218. public maxVertexUniformVectors: number;
  219. public maxFragmentUniformVectors: number;
  220. public standardDerivatives: boolean;
  221. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  222. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  223. public etc1: any; //WEBGL_compressed_texture_etc1;
  224. public etc2: any; //WEBGL_compressed_texture_etc;
  225. public astc: any; //WEBGL_compressed_texture_astc;
  226. public textureFloat: boolean;
  227. public vertexArrayObject: boolean;
  228. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  229. public maxAnisotropy: number;
  230. public instancedArrays: boolean;
  231. public uintIndices: boolean;
  232. public highPrecisionShaderSupported: boolean;
  233. public fragmentDepthSupported: boolean;
  234. public textureFloatLinearFiltering: boolean;
  235. public textureFloatRender: boolean;
  236. public textureHalfFloat: boolean;
  237. public textureHalfFloatLinearFiltering: boolean;
  238. public textureHalfFloatRender: boolean;
  239. public textureLOD: boolean;
  240. public drawBuffersExtension: boolean;
  241. public depthTextureExtension: boolean;
  242. public colorBufferFloat: boolean;
  243. public timerQuery: EXT_disjoint_timer_query;
  244. public canUseTimestampForTimerQuery: boolean;
  245. }
  246. export interface EngineOptions extends WebGLContextAttributes {
  247. limitDeviceRatio?: number;
  248. autoEnableWebVR?: boolean;
  249. disableWebGL2Support?: boolean;
  250. audioEngine?: boolean;
  251. deterministicLockstep?: boolean;
  252. lockstepMaxSteps?: number;
  253. doNotHandleContextLost?: boolean;
  254. }
  255. export interface IDisplayChangedEventArgs {
  256. vrDisplay: Nullable<any>;
  257. vrSupported: boolean;
  258. }
  259. /**
  260. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  261. */
  262. export class Engine {
  263. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  264. public static ExceptionList = [
  265. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  266. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  267. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  268. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  269. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  270. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  271. ];
  272. public static Instances = new Array<Engine>();
  273. public static get LastCreatedEngine(): Nullable<Engine> {
  274. if (Engine.Instances.length === 0) {
  275. return null;
  276. }
  277. return Engine.Instances[Engine.Instances.length - 1];
  278. }
  279. public static get LastCreatedScene(): Nullable<Scene> {
  280. var lastCreatedEngine = Engine.LastCreatedEngine;
  281. if (!lastCreatedEngine) {
  282. return null;
  283. }
  284. if (lastCreatedEngine.scenes.length === 0) {
  285. return null;
  286. }
  287. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  288. }
  289. /**
  290. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  291. */
  292. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  293. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  294. var engine = Engine.Instances[engineIndex];
  295. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  296. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  297. }
  298. }
  299. }
  300. // Const statics
  301. private static _ALPHA_DISABLE = 0;
  302. private static _ALPHA_ADD = 1;
  303. private static _ALPHA_COMBINE = 2;
  304. private static _ALPHA_SUBTRACT = 3;
  305. private static _ALPHA_MULTIPLY = 4;
  306. private static _ALPHA_MAXIMIZED = 5;
  307. private static _ALPHA_ONEONE = 6;
  308. private static _ALPHA_PREMULTIPLIED = 7;
  309. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  310. private static _ALPHA_INTERPOLATE = 9;
  311. private static _ALPHA_SCREENMODE = 10;
  312. private static _DELAYLOADSTATE_NONE = 0;
  313. private static _DELAYLOADSTATE_LOADED = 1;
  314. private static _DELAYLOADSTATE_LOADING = 2;
  315. private static _DELAYLOADSTATE_NOTLOADED = 4;
  316. private static _TEXTUREFORMAT_ALPHA = 0;
  317. private static _TEXTUREFORMAT_LUMINANCE = 1;
  318. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  319. private static _TEXTUREFORMAT_RGB = 4;
  320. private static _TEXTUREFORMAT_RGBA = 5;
  321. private static _TEXTUREFORMAT_R32F = 6;
  322. private static _TEXTUREFORMAT_RG32F = 7;
  323. private static _TEXTUREFORMAT_RGB32F = 8;
  324. private static _TEXTUREFORMAT_RGBA32F = 9;
  325. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  326. private static _TEXTURETYPE_FLOAT = 1;
  327. private static _TEXTURETYPE_HALF_FLOAT = 2;
  328. // Depht or Stencil test Constants.
  329. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  330. 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.
  331. 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.
  332. 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.
  333. 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.
  334. 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.
  335. 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.
  336. 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.
  337. public static get NEVER(): number {
  338. return Engine._NEVER;
  339. }
  340. public static get ALWAYS(): number {
  341. return Engine._ALWAYS;
  342. }
  343. public static get LESS(): number {
  344. return Engine._LESS;
  345. }
  346. public static get EQUAL(): number {
  347. return Engine._EQUAL;
  348. }
  349. public static get LEQUAL(): number {
  350. return Engine._LEQUAL;
  351. }
  352. public static get GREATER(): number {
  353. return Engine._GREATER;
  354. }
  355. public static get GEQUAL(): number {
  356. return Engine._GEQUAL;
  357. }
  358. public static get NOTEQUAL(): number {
  359. return Engine._NOTEQUAL;
  360. }
  361. // Stencil Actions Constants.
  362. private static _KEEP = 0x1E00;
  363. private static _REPLACE = 0x1E01;
  364. private static _INCR = 0x1E02;
  365. private static _DECR = 0x1E03;
  366. private static _INVERT = 0x150A;
  367. private static _INCR_WRAP = 0x8507;
  368. private static _DECR_WRAP = 0x8508;
  369. public static get KEEP(): number {
  370. return Engine._KEEP;
  371. }
  372. public static get REPLACE(): number {
  373. return Engine._REPLACE;
  374. }
  375. public static get INCR(): number {
  376. return Engine._INCR;
  377. }
  378. public static get DECR(): number {
  379. return Engine._DECR;
  380. }
  381. public static get INVERT(): number {
  382. return Engine._INVERT;
  383. }
  384. public static get INCR_WRAP(): number {
  385. return Engine._INCR_WRAP;
  386. }
  387. public static get DECR_WRAP(): number {
  388. return Engine._DECR_WRAP;
  389. }
  390. public static get ALPHA_DISABLE(): number {
  391. return Engine._ALPHA_DISABLE;
  392. }
  393. public static get ALPHA_ONEONE(): number {
  394. return Engine._ALPHA_ONEONE;
  395. }
  396. public static get ALPHA_ADD(): number {
  397. return Engine._ALPHA_ADD;
  398. }
  399. public static get ALPHA_COMBINE(): number {
  400. return Engine._ALPHA_COMBINE;
  401. }
  402. public static get ALPHA_SUBTRACT(): number {
  403. return Engine._ALPHA_SUBTRACT;
  404. }
  405. public static get ALPHA_MULTIPLY(): number {
  406. return Engine._ALPHA_MULTIPLY;
  407. }
  408. public static get ALPHA_MAXIMIZED(): number {
  409. return Engine._ALPHA_MAXIMIZED;
  410. }
  411. public static get ALPHA_PREMULTIPLIED(): number {
  412. return Engine._ALPHA_PREMULTIPLIED;
  413. }
  414. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  415. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  416. }
  417. public static get ALPHA_INTERPOLATE(): number {
  418. return Engine._ALPHA_INTERPOLATE;
  419. }
  420. public static get ALPHA_SCREENMODE(): number {
  421. return Engine._ALPHA_SCREENMODE;
  422. }
  423. public static get DELAYLOADSTATE_NONE(): number {
  424. return Engine._DELAYLOADSTATE_NONE;
  425. }
  426. public static get DELAYLOADSTATE_LOADED(): number {
  427. return Engine._DELAYLOADSTATE_LOADED;
  428. }
  429. public static get DELAYLOADSTATE_LOADING(): number {
  430. return Engine._DELAYLOADSTATE_LOADING;
  431. }
  432. public static get DELAYLOADSTATE_NOTLOADED(): number {
  433. return Engine._DELAYLOADSTATE_NOTLOADED;
  434. }
  435. public static get TEXTUREFORMAT_ALPHA(): number {
  436. return Engine._TEXTUREFORMAT_ALPHA;
  437. }
  438. public static get TEXTUREFORMAT_LUMINANCE(): number {
  439. return Engine._TEXTUREFORMAT_LUMINANCE;
  440. }
  441. /**
  442. * R32F
  443. */
  444. public static get TEXTUREFORMAT_R32F(): number {
  445. return Engine._TEXTUREFORMAT_R32F;
  446. }
  447. /**
  448. * RG32F
  449. */
  450. public static get TEXTUREFORMAT_RG32F(): number {
  451. return Engine._TEXTUREFORMAT_RG32F;
  452. }
  453. /**
  454. * RGB32F
  455. */
  456. public static get TEXTUREFORMAT_RGB32F(): number {
  457. return Engine._TEXTUREFORMAT_RGB32F;
  458. }
  459. /**
  460. * RGBA32F
  461. */
  462. public static get TEXTUREFORMAT_RGBA32F(): number {
  463. return Engine._TEXTUREFORMAT_RGBA32F;
  464. }
  465. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  466. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  467. }
  468. public static get TEXTUREFORMAT_RGB(): number {
  469. return Engine._TEXTUREFORMAT_RGB;
  470. }
  471. public static get TEXTUREFORMAT_RGBA(): number {
  472. return Engine._TEXTUREFORMAT_RGBA;
  473. }
  474. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  475. return Engine._TEXTURETYPE_UNSIGNED_INT;
  476. }
  477. public static get TEXTURETYPE_FLOAT(): number {
  478. return Engine._TEXTURETYPE_FLOAT;
  479. }
  480. public static get TEXTURETYPE_HALF_FLOAT(): number {
  481. return Engine._TEXTURETYPE_HALF_FLOAT;
  482. }
  483. // Texture rescaling mode
  484. private static _SCALEMODE_FLOOR = 1;
  485. private static _SCALEMODE_NEAREST = 2;
  486. private static _SCALEMODE_CEILING = 3;
  487. public static get SCALEMODE_FLOOR(): number {
  488. return Engine._SCALEMODE_FLOOR;
  489. }
  490. public static get SCALEMODE_NEAREST(): number {
  491. return Engine._SCALEMODE_NEAREST;
  492. }
  493. public static get SCALEMODE_CEILING(): number {
  494. return Engine._SCALEMODE_CEILING;
  495. }
  496. public static get Version(): string {
  497. return "3.2.0-alphaB";
  498. }
  499. // Updatable statics so stick with vars here
  500. public static CollisionsEpsilon = 0.001;
  501. public static CodeRepository = "src/";
  502. public static ShadersRepository = "src/Shaders/";
  503. // Public members
  504. public forcePOTTextures = false;
  505. public isFullscreen = false;
  506. public isPointerLock = false;
  507. public cullBackFaces = true;
  508. public renderEvenInBackground = true;
  509. public preventCacheWipeBetweenFrames = false;
  510. // To enable/disable IDB support and avoid XHR on .manifest
  511. public enableOfflineSupport = false;
  512. public scenes = new Array<Scene>();
  513. public postProcesses = new Array<PostProcess>();
  514. // Observables
  515. /**
  516. * Observable event triggered each time the rendering canvas is resized
  517. */
  518. public onResizeObservable = new Observable<Engine>();
  519. /**
  520. * Observable event triggered each time the canvas loses focus
  521. */
  522. public onCanvasBlurObservable = new Observable<Engine>();
  523. /**
  524. * Observable event triggered each time the canvas gains focus
  525. */
  526. public onCanvasFocusObservable = new Observable<Engine>();
  527. /**
  528. * Observable event triggered each time the canvas receives pointerout event
  529. */
  530. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  531. /**
  532. * Observable event triggered before each texture is initialized
  533. */
  534. public onBeforeTextureInitObservable = new Observable<Texture>();
  535. //WebVR
  536. private _vrDisplay: any = undefined;
  537. private _vrSupported: boolean = false;
  538. private _oldSize: Size;
  539. private _oldHardwareScaleFactor: number;
  540. private _vrExclusivePointerMode = false;
  541. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  542. public get isInVRExclusivePointerMode(): boolean {
  543. return this._vrExclusivePointerMode;
  544. }
  545. // Uniform buffers list
  546. public disableUniformBuffers = false;
  547. public _uniformBuffers = new Array<UniformBuffer>();
  548. public get supportsUniformBuffers(): boolean {
  549. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  550. }
  551. // Observables
  552. /**
  553. * Observable raised when the engine begins a new frame
  554. */
  555. public onBeginFrameObservable = new Observable<Engine>();
  556. /**
  557. * Observable raised when the engine ends the current frame
  558. */
  559. public onEndFrameObservable = new Observable<Engine>();
  560. /**
  561. * Observable raised when the engine is about to compile a shader
  562. */
  563. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  564. /**
  565. * Observable raised when the engine has jsut compiled a shader
  566. */
  567. public onAfterShaderCompilationObservable = new Observable<Engine>();
  568. // Private Members
  569. private _gl: WebGLRenderingContext;
  570. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  571. private _windowIsBackground = false;
  572. private _webGLVersion = 1.0;
  573. public get needPOTTextures(): boolean {
  574. return this._webGLVersion < 2 || this.forcePOTTextures;
  575. }
  576. private _badOS = false;
  577. public get badOS(): boolean {
  578. return this._badOS;
  579. }
  580. private _badDesktopOS = false;
  581. public get badDesktopOS(): boolean {
  582. return this._badDesktopOS;
  583. }
  584. /**
  585. * Gets or sets a value indicating if we want to disable texture binding optmization.
  586. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  587. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  588. */
  589. public disableTextureBindingOptimization = false;
  590. public static audioEngine: AudioEngine;
  591. // Focus
  592. private _onFocus: () => void;
  593. private _onBlur: () => void;
  594. private _onCanvasPointerOut: (event: PointerEvent) => void;
  595. private _onCanvasBlur: () => void;
  596. private _onCanvasFocus: () => void;
  597. private _onFullscreenChange: () => void;
  598. private _onPointerLockChange: () => void;
  599. private _onVRDisplayPointerRestricted: () => void;
  600. private _onVRDisplayPointerUnrestricted: () => void;
  601. // VRDisplay connection
  602. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  603. private _onVrDisplayDisconnect: Nullable<() => void>;
  604. private _onVrDisplayPresentChange: Nullable<() => void>;
  605. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  606. public onVRRequestPresentComplete = new Observable<boolean>();
  607. public onVRRequestPresentStart = new Observable<Engine>();
  608. private _hardwareScalingLevel: number;
  609. protected _caps: EngineCapabilities;
  610. private _pointerLockRequested: boolean;
  611. private _isStencilEnable: boolean;
  612. private _colorWrite = true;
  613. private _loadingScreen: ILoadingScreen;
  614. public _drawCalls = new PerfCounter();
  615. public _textureCollisions = new PerfCounter();
  616. private _glVersion: string;
  617. private _glRenderer: string;
  618. private _glVendor: string;
  619. private _videoTextureSupported: boolean;
  620. private _renderingQueueLaunched = false;
  621. private _activeRenderLoops = new Array<() => void>();
  622. // Deterministic lockstepMaxSteps
  623. private _deterministicLockstep: boolean = false;
  624. private _lockstepMaxSteps: number = 4;
  625. // Lost context
  626. public onContextLostObservable = new Observable<Engine>();
  627. public onContextRestoredObservable = new Observable<Engine>();
  628. private _onContextLost: (evt: Event) => void;
  629. private _onContextRestored: (evt: Event) => void;
  630. private _contextWasLost = false;
  631. private _doNotHandleContextLost = false;
  632. // FPS
  633. private _performanceMonitor = new PerformanceMonitor();
  634. private _fps = 60;
  635. private _deltaTime = 0;
  636. /**
  637. * Turn this value on if you want to pause FPS computation when in background
  638. */
  639. public disablePerformanceMonitorInBackground = false;
  640. public get performanceMonitor(): PerformanceMonitor {
  641. return this._performanceMonitor;
  642. }
  643. // States
  644. protected _depthCullingState = new _DepthCullingState();
  645. protected _stencilState = new _StencilState();
  646. protected _alphaState = new _AlphaState();
  647. protected _alphaMode = Engine.ALPHA_DISABLE;
  648. // Cache
  649. private _internalTexturesCache = new Array<InternalTexture>();
  650. protected _activeChannel = 0;
  651. private _currentTextureChannel = -1;
  652. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  653. protected _currentEffect: Nullable<Effect>;
  654. protected _currentProgram: Nullable<WebGLProgram>;
  655. private _compiledEffects: { [key: string]: Effect } = {}
  656. private _vertexAttribArraysEnabled: boolean[] = [];
  657. protected _cachedViewport: Nullable<Viewport>;
  658. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  659. protected _cachedVertexBuffers: any;
  660. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  661. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  662. protected _currentRenderTarget: Nullable<InternalTexture>;
  663. private _uintIndicesCurrentlySet = false;
  664. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  665. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  666. private _currentBufferPointers = new Array<BufferPointer>();
  667. private _currentInstanceLocations = new Array<number>();
  668. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  669. private _textureUnits: Int32Array;
  670. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  671. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  672. private _workingCanvas: Nullable<HTMLCanvasElement>;
  673. private _workingContext: Nullable<CanvasRenderingContext2D>;
  674. private _rescalePostProcess: PassPostProcess;
  675. private _dummyFramebuffer: WebGLFramebuffer;
  676. private _externalData: StringDictionary<Object>;
  677. private _bindedRenderFunction: any;
  678. private _vaoRecordInProgress = false;
  679. private _mustWipeVertexAttributes = false;
  680. private _emptyTexture: Nullable<InternalTexture>;
  681. private _emptyCubeTexture: Nullable<InternalTexture>;
  682. private _emptyTexture3D: Nullable<InternalTexture>;
  683. private _frameHandler: number;
  684. private _nextFreeTextureSlots = new Array<number>();
  685. private _maxSimultaneousTextures = 0;
  686. private _activeRequests = new Array<IFileRequest>();
  687. // Hardware supported Compressed Textures
  688. private _texturesSupported = new Array<string>();
  689. private _textureFormatInUse: Nullable<string>;
  690. public get texturesSupported(): Array<string> {
  691. return this._texturesSupported;
  692. }
  693. public get textureFormatInUse(): Nullable<string> {
  694. return this._textureFormatInUse;
  695. }
  696. public get currentViewport(): Nullable<Viewport> {
  697. return this._cachedViewport;
  698. }
  699. // Empty texture
  700. public get emptyTexture(): InternalTexture {
  701. if (!this._emptyTexture) {
  702. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  703. }
  704. return this._emptyTexture;
  705. }
  706. public get emptyTexture3D(): InternalTexture {
  707. if (!this._emptyTexture3D) {
  708. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  709. }
  710. return this._emptyTexture3D;
  711. }
  712. public get emptyCubeTexture(): InternalTexture {
  713. if (!this._emptyCubeTexture) {
  714. var faceData = new Uint8Array(4);
  715. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  716. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  717. }
  718. return this._emptyCubeTexture;
  719. }
  720. /**
  721. * @constructor
  722. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  723. * @param antialias defines enable antialiasing (default: false)
  724. * @param options defines further options to be sent to the getContext() function
  725. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  726. */
  727. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  728. // Register promises
  729. PromisePolyfill.Apply();
  730. let canvas: Nullable<HTMLCanvasElement> = null;
  731. Engine.Instances.push(this);
  732. if (!canvasOrContext) {
  733. return;
  734. }
  735. options = options || {};
  736. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  737. canvas = <HTMLCanvasElement>canvasOrContext;
  738. this._renderingCanvas = canvas;
  739. if (antialias != null) {
  740. options.antialias = antialias;
  741. }
  742. if (options.deterministicLockstep === undefined) {
  743. options.deterministicLockstep = false;
  744. }
  745. if (options.lockstepMaxSteps === undefined) {
  746. options.lockstepMaxSteps = 4;
  747. }
  748. if (options.preserveDrawingBuffer === undefined) {
  749. options.preserveDrawingBuffer = false;
  750. }
  751. if (options.audioEngine === undefined) {
  752. options.audioEngine = true;
  753. }
  754. if (options.stencil === undefined) {
  755. options.stencil = true;
  756. }
  757. this._deterministicLockstep = options.deterministicLockstep;
  758. this._lockstepMaxSteps = options.lockstepMaxSteps;
  759. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  760. // Exceptions
  761. if (navigator && navigator.userAgent) {
  762. let ua = navigator.userAgent;
  763. for (var exception of Engine.ExceptionList) {
  764. let key = exception.key;
  765. let targets = exception.targets;
  766. if (ua.indexOf(key) > -1) {
  767. if (exception.capture && exception.captureConstraint) {
  768. let capture = exception.capture;
  769. let constraint = exception.captureConstraint;
  770. let regex = new RegExp(capture);
  771. let matches = regex.exec(ua);
  772. if (matches && matches.length > 0) {
  773. let capturedValue = parseInt(matches[matches.length - 1]);
  774. if (capturedValue >= constraint) {
  775. continue;
  776. }
  777. }
  778. }
  779. for (var target of targets) {
  780. switch (target) {
  781. case "uniformBuffer":
  782. this.disableUniformBuffers = true;
  783. break;
  784. case "textureBindingOptimization":
  785. this.disableTextureBindingOptimization = true;
  786. break;
  787. }
  788. }
  789. }
  790. }
  791. }
  792. // GL
  793. if (!options.disableWebGL2Support) {
  794. try {
  795. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  796. if (this._gl) {
  797. this._webGLVersion = 2.0;
  798. }
  799. } catch (e) {
  800. // Do nothing
  801. }
  802. }
  803. if (!this._gl) {
  804. if (!canvas) {
  805. throw new Error("The provided canvas is null or undefined.");
  806. }
  807. try {
  808. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  809. } catch (e) {
  810. throw new Error("WebGL not supported");
  811. }
  812. }
  813. if (!this._gl) {
  814. throw new Error("WebGL not supported");
  815. }
  816. this._onCanvasFocus = () => {
  817. this.onCanvasFocusObservable.notifyObservers(this);
  818. }
  819. this._onCanvasBlur = () => {
  820. this.onCanvasBlurObservable.notifyObservers(this);
  821. }
  822. canvas.addEventListener("focus", this._onCanvasFocus);
  823. canvas.addEventListener("blur", this._onCanvasBlur);
  824. this._onBlur = () => {
  825. if (this.disablePerformanceMonitorInBackground) {
  826. this._performanceMonitor.disable();
  827. }
  828. this._windowIsBackground = true;
  829. };
  830. this._onFocus = () => {
  831. if (this.disablePerformanceMonitorInBackground) {
  832. this._performanceMonitor.enable();
  833. }
  834. this._windowIsBackground = false;
  835. };
  836. this._onCanvasPointerOut = (ev) => {
  837. this.onCanvasPointerOutObservable.notifyObservers(ev);
  838. };
  839. window.addEventListener("blur", this._onBlur);
  840. window.addEventListener("focus", this._onFocus);
  841. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  842. // Context lost
  843. if (!this._doNotHandleContextLost) {
  844. this._onContextLost = (evt: Event) => {
  845. evt.preventDefault();
  846. this._contextWasLost = true;
  847. Tools.Warn("WebGL context lost.");
  848. this.onContextLostObservable.notifyObservers(this);
  849. };
  850. this._onContextRestored = (evt: Event) => {
  851. // Adding a timeout to avoid race condition at browser level
  852. setTimeout(() => {
  853. // Rebuild gl context
  854. this._initGLContext();
  855. // Rebuild effects
  856. this._rebuildEffects();
  857. // Rebuild textures
  858. this._rebuildInternalTextures();
  859. // Rebuild buffers
  860. this._rebuildBuffers();
  861. // Cache
  862. this.wipeCaches(true);
  863. Tools.Warn("WebGL context successfully restored.");
  864. this.onContextRestoredObservable.notifyObservers(this);
  865. this._contextWasLost = false;
  866. }, 0);
  867. };
  868. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  869. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  870. }
  871. } else {
  872. this._gl = <WebGLRenderingContext>canvasOrContext;
  873. this._renderingCanvas = this._gl.canvas
  874. if (this._gl.renderbufferStorageMultisample) {
  875. this._webGLVersion = 2.0;
  876. }
  877. options.stencil = this._gl.getContextAttributes().stencil;
  878. }
  879. // Viewport
  880. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  881. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  882. this.resize();
  883. this._isStencilEnable = options.stencil ? true : false;
  884. this._initGLContext();
  885. if (canvas) {
  886. // Fullscreen
  887. this._onFullscreenChange = () => {
  888. if (document.fullscreen !== undefined) {
  889. this.isFullscreen = document.fullscreen;
  890. } else if (document.mozFullScreen !== undefined) {
  891. this.isFullscreen = document.mozFullScreen;
  892. } else if (document.webkitIsFullScreen !== undefined) {
  893. this.isFullscreen = document.webkitIsFullScreen;
  894. } else if (document.msIsFullScreen !== undefined) {
  895. this.isFullscreen = document.msIsFullScreen;
  896. }
  897. // Pointer lock
  898. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  899. canvas.requestPointerLock = canvas.requestPointerLock ||
  900. canvas.msRequestPointerLock ||
  901. canvas.mozRequestPointerLock ||
  902. canvas.webkitRequestPointerLock;
  903. if (canvas.requestPointerLock) {
  904. canvas.requestPointerLock();
  905. }
  906. }
  907. };
  908. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  909. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  910. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  911. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  912. // Pointer lock
  913. this._onPointerLockChange = () => {
  914. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  915. document.webkitPointerLockElement === canvas ||
  916. document.msPointerLockElement === canvas ||
  917. document.pointerLockElement === canvas
  918. );
  919. };
  920. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  921. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  922. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  923. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  924. this._onVRDisplayPointerRestricted = () => {
  925. if (canvas) {
  926. canvas.requestPointerLock();
  927. }
  928. }
  929. this._onVRDisplayPointerUnrestricted = () => {
  930. document.exitPointerLock();
  931. }
  932. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  933. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  934. }
  935. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  936. Engine.audioEngine = new AudioEngine();
  937. }
  938. // Prepare buffer pointers
  939. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  940. this._currentBufferPointers[i] = new BufferPointer();
  941. }
  942. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  943. // Load WebVR Devices
  944. if (options.autoEnableWebVR) {
  945. this.initWebVR();
  946. }
  947. // Detect if we are running on a faulty buggy OS.
  948. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  949. // Detect if we are running on a faulty buggy desktop OS.
  950. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  951. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  952. this.enableOfflineSupport = (Database !== undefined);
  953. }
  954. private _rebuildInternalTextures(): void {
  955. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  956. for (var internalTexture of currentState) {
  957. internalTexture._rebuild();
  958. }
  959. }
  960. private _rebuildEffects(): void {
  961. for (var key in this._compiledEffects) {
  962. let effect = <Effect>this._compiledEffects[key];
  963. effect._prepareEffect();
  964. }
  965. Effect.ResetCache();
  966. }
  967. private _rebuildBuffers(): void {
  968. // Index / Vertex
  969. for (var scene of this.scenes) {
  970. scene.resetCachedMaterial();
  971. scene._rebuildGeometries();
  972. scene._rebuildTextures();
  973. }
  974. // Uniforms
  975. for (var uniformBuffer of this._uniformBuffers) {
  976. uniformBuffer._rebuild();
  977. }
  978. }
  979. private _initGLContext(): void {
  980. // Caps
  981. this._caps = new EngineCapabilities();
  982. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  983. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  984. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  985. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  986. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  987. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  988. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  989. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  990. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  991. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  992. // Infos
  993. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  994. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  995. if (rendererInfo != null) {
  996. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  997. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  998. }
  999. if (!this._glVendor) {
  1000. this._glVendor = "Unknown vendor";
  1001. }
  1002. if (!this._glRenderer) {
  1003. this._glRenderer = "Unknown renderer";
  1004. }
  1005. // Constants
  1006. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1007. if (this._gl.RGBA16F !== 0x881A) {
  1008. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1009. }
  1010. if (this._gl.RGBA32F !== 0x8814) {
  1011. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1012. }
  1013. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1014. this._gl.DEPTH24_STENCIL8 = 35056;
  1015. }
  1016. // Extensions
  1017. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1018. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1019. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1020. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1021. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1022. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1023. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1024. 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');
  1025. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1026. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1027. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1028. this._caps.highPrecisionShaderSupported = true;
  1029. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1030. if (this._caps.timerQuery) {
  1031. if (this._webGLVersion === 1) {
  1032. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1033. }
  1034. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1035. }
  1036. // Checks if some of the format renders first to allow the use of webgl inspector.
  1037. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1038. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  1039. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  1040. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  1041. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  1042. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  1043. if (this._webGLVersion > 1) {
  1044. this._gl.HALF_FLOAT_OES = 0x140B;
  1045. }
  1046. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1047. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  1048. // Draw buffers
  1049. if (this._webGLVersion > 1) {
  1050. this._caps.drawBuffersExtension = true;
  1051. } else {
  1052. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1053. if (drawBuffersExtension !== null) {
  1054. this._caps.drawBuffersExtension = true;
  1055. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1056. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1057. for (var i = 0; i < 16; i++) {
  1058. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1059. }
  1060. } else {
  1061. this._caps.drawBuffersExtension = false;
  1062. }
  1063. }
  1064. // Depth Texture
  1065. if (this._webGLVersion > 1) {
  1066. this._caps.depthTextureExtension = true;
  1067. } else {
  1068. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1069. if (depthTextureExtension != null) {
  1070. this._caps.depthTextureExtension = true;
  1071. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1072. }
  1073. }
  1074. // Vertex array object
  1075. if (this._webGLVersion > 1) {
  1076. this._caps.vertexArrayObject = true;
  1077. } else {
  1078. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1079. if (vertexArrayObjectExtension != null) {
  1080. this._caps.vertexArrayObject = true;
  1081. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1082. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1083. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1084. } else {
  1085. this._caps.vertexArrayObject = false;
  1086. }
  1087. }
  1088. // Instances count
  1089. if (this._webGLVersion > 1) {
  1090. this._caps.instancedArrays = true;
  1091. } else {
  1092. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1093. if (instanceExtension != null) {
  1094. this._caps.instancedArrays = true;
  1095. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1096. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1097. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1098. } else {
  1099. this._caps.instancedArrays = false;
  1100. }
  1101. }
  1102. // Intelligently add supported compressed formats in order to check for.
  1103. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1104. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1105. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1106. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1107. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1108. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1109. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1110. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1111. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1112. if (this._gl.getShaderPrecisionFormat) {
  1113. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1114. if (highp) {
  1115. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1116. }
  1117. }
  1118. // Depth buffer
  1119. this.setDepthBuffer(true);
  1120. this.setDepthFunctionToLessOrEqual();
  1121. this.setDepthWrite(true);
  1122. // Texture maps
  1123. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1124. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1125. this._nextFreeTextureSlots.push(slot);
  1126. }
  1127. }
  1128. public get webGLVersion(): number {
  1129. return this._webGLVersion;
  1130. }
  1131. /**
  1132. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1133. */
  1134. public get isStencilEnable(): boolean {
  1135. return this._isStencilEnable;
  1136. }
  1137. private _prepareWorkingCanvas(): void {
  1138. if (this._workingCanvas) {
  1139. return;
  1140. }
  1141. this._workingCanvas = document.createElement("canvas");
  1142. let context = this._workingCanvas.getContext("2d");
  1143. if (context) {
  1144. this._workingContext = context;
  1145. }
  1146. }
  1147. public resetTextureCache() {
  1148. for (var key in this._boundTexturesCache) {
  1149. let boundTexture = this._boundTexturesCache[key];
  1150. if (boundTexture) {
  1151. this._removeDesignatedSlot(boundTexture);
  1152. }
  1153. this._boundTexturesCache[key] = null;
  1154. }
  1155. if (!this.disableTextureBindingOptimization) {
  1156. this._nextFreeTextureSlots = [];
  1157. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1158. this._nextFreeTextureSlots.push(slot);
  1159. }
  1160. }
  1161. this._currentTextureChannel = -1;
  1162. }
  1163. public isDeterministicLockStep(): boolean {
  1164. return this._deterministicLockstep;
  1165. }
  1166. public getLockstepMaxSteps(): number {
  1167. return this._lockstepMaxSteps;
  1168. }
  1169. public getGlInfo() {
  1170. return {
  1171. vendor: this._glVendor,
  1172. renderer: this._glRenderer,
  1173. version: this._glVersion
  1174. }
  1175. }
  1176. public getAspectRatio(camera: Camera, useScreen = false): number {
  1177. var viewport = camera.viewport;
  1178. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1179. }
  1180. public getRenderWidth(useScreen = false): number {
  1181. if (!useScreen && this._currentRenderTarget) {
  1182. return this._currentRenderTarget.width;
  1183. }
  1184. return this._gl.drawingBufferWidth;
  1185. }
  1186. public getRenderHeight(useScreen = false): number {
  1187. if (!useScreen && this._currentRenderTarget) {
  1188. return this._currentRenderTarget.height;
  1189. }
  1190. return this._gl.drawingBufferHeight;
  1191. }
  1192. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1193. return this._renderingCanvas;
  1194. }
  1195. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1196. if (!this._renderingCanvas) {
  1197. return null;
  1198. }
  1199. return this._renderingCanvas.getBoundingClientRect();
  1200. }
  1201. public setHardwareScalingLevel(level: number): void {
  1202. this._hardwareScalingLevel = level;
  1203. this.resize();
  1204. }
  1205. public getHardwareScalingLevel(): number {
  1206. return this._hardwareScalingLevel;
  1207. }
  1208. public getLoadedTexturesCache(): InternalTexture[] {
  1209. return this._internalTexturesCache;
  1210. }
  1211. public getCaps(): EngineCapabilities {
  1212. return this._caps;
  1213. }
  1214. /** The number of draw calls submitted last frame */
  1215. public get drawCalls(): number {
  1216. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1217. return 0;
  1218. }
  1219. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1220. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1221. return null;
  1222. }
  1223. public getDepthFunction(): Nullable<number> {
  1224. return this._depthCullingState.depthFunc;
  1225. }
  1226. public setDepthFunction(depthFunc: number) {
  1227. this._depthCullingState.depthFunc = depthFunc;
  1228. }
  1229. public setDepthFunctionToGreater(): void {
  1230. this._depthCullingState.depthFunc = this._gl.GREATER;
  1231. }
  1232. public setDepthFunctionToGreaterOrEqual(): void {
  1233. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1234. }
  1235. public setDepthFunctionToLess(): void {
  1236. this._depthCullingState.depthFunc = this._gl.LESS;
  1237. }
  1238. public setDepthFunctionToLessOrEqual(): void {
  1239. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1240. }
  1241. public getStencilBuffer(): boolean {
  1242. return this._stencilState.stencilTest;
  1243. }
  1244. public setStencilBuffer(enable: boolean): void {
  1245. this._stencilState.stencilTest = enable;
  1246. }
  1247. public getStencilMask(): number {
  1248. return this._stencilState.stencilMask;
  1249. }
  1250. public setStencilMask(mask: number): void {
  1251. this._stencilState.stencilMask = mask;
  1252. }
  1253. public getStencilFunction(): number {
  1254. return this._stencilState.stencilFunc;
  1255. }
  1256. public getStencilFunctionReference(): number {
  1257. return this._stencilState.stencilFuncRef;
  1258. }
  1259. public getStencilFunctionMask(): number {
  1260. return this._stencilState.stencilFuncMask;
  1261. }
  1262. public setStencilFunction(stencilFunc: number) {
  1263. this._stencilState.stencilFunc = stencilFunc;
  1264. }
  1265. public setStencilFunctionReference(reference: number) {
  1266. this._stencilState.stencilFuncRef = reference;
  1267. }
  1268. public setStencilFunctionMask(mask: number) {
  1269. this._stencilState.stencilFuncMask = mask;
  1270. }
  1271. public getStencilOperationFail(): number {
  1272. return this._stencilState.stencilOpStencilFail;
  1273. }
  1274. public getStencilOperationDepthFail(): number {
  1275. return this._stencilState.stencilOpDepthFail;
  1276. }
  1277. public getStencilOperationPass(): number {
  1278. return this._stencilState.stencilOpStencilDepthPass;
  1279. }
  1280. public setStencilOperationFail(operation: number): void {
  1281. this._stencilState.stencilOpStencilFail = operation;
  1282. }
  1283. public setStencilOperationDepthFail(operation: number): void {
  1284. this._stencilState.stencilOpDepthFail = operation;
  1285. }
  1286. public setStencilOperationPass(operation: number): void {
  1287. this._stencilState.stencilOpStencilDepthPass = operation;
  1288. }
  1289. public setDitheringState(value: boolean): void {
  1290. if (value) {
  1291. this._gl.enable(this._gl.DITHER);
  1292. } else {
  1293. this._gl.disable(this._gl.DITHER);
  1294. }
  1295. }
  1296. public setRasterizerState(value: boolean): void {
  1297. if (value) {
  1298. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1299. } else {
  1300. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1301. }
  1302. }
  1303. /**
  1304. * stop executing a render loop function and remove it from the execution array
  1305. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1306. */
  1307. public stopRenderLoop(renderFunction?: () => void): void {
  1308. if (!renderFunction) {
  1309. this._activeRenderLoops = [];
  1310. return;
  1311. }
  1312. var index = this._activeRenderLoops.indexOf(renderFunction);
  1313. if (index >= 0) {
  1314. this._activeRenderLoops.splice(index, 1);
  1315. }
  1316. }
  1317. public _renderLoop(): void {
  1318. if (!this._contextWasLost) {
  1319. var shouldRender = true;
  1320. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1321. shouldRender = false;
  1322. }
  1323. if (shouldRender) {
  1324. // Start new frame
  1325. this.beginFrame();
  1326. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1327. var renderFunction = this._activeRenderLoops[index];
  1328. renderFunction();
  1329. }
  1330. // Present
  1331. this.endFrame();
  1332. }
  1333. }
  1334. if (this._activeRenderLoops.length > 0) {
  1335. // Register new frame
  1336. var requester = null;
  1337. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1338. requester = this._vrDisplay;
  1339. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1340. } else {
  1341. this._renderingQueueLaunched = false;
  1342. }
  1343. }
  1344. /**
  1345. * Register and execute a render loop. The engine can have more than one render function.
  1346. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1347. * @example
  1348. * engine.runRenderLoop(function () {
  1349. * scene.render()
  1350. * })
  1351. */
  1352. public runRenderLoop(renderFunction: () => void): void {
  1353. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1354. return;
  1355. }
  1356. this._activeRenderLoops.push(renderFunction);
  1357. if (!this._renderingQueueLaunched) {
  1358. this._renderingQueueLaunched = true;
  1359. this._bindedRenderFunction = this._renderLoop.bind(this);
  1360. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1361. }
  1362. }
  1363. /**
  1364. * Toggle full screen mode.
  1365. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1366. * @param {any} options - an options object to be sent to the requestFullscreen function
  1367. */
  1368. public switchFullscreen(requestPointerLock: boolean): void {
  1369. if (this.isFullscreen) {
  1370. Tools.ExitFullscreen();
  1371. } else {
  1372. this._pointerLockRequested = requestPointerLock;
  1373. if (this._renderingCanvas) {
  1374. Tools.RequestFullscreen(this._renderingCanvas);
  1375. }
  1376. }
  1377. }
  1378. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1379. this.applyStates();
  1380. var mode = 0;
  1381. if (backBuffer && color) {
  1382. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1383. mode |= this._gl.COLOR_BUFFER_BIT;
  1384. }
  1385. if (depth) {
  1386. this._gl.clearDepth(1.0);
  1387. mode |= this._gl.DEPTH_BUFFER_BIT;
  1388. }
  1389. if (stencil) {
  1390. this._gl.clearStencil(0);
  1391. mode |= this._gl.STENCIL_BUFFER_BIT;
  1392. }
  1393. this._gl.clear(mode);
  1394. }
  1395. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1396. let gl = this._gl;
  1397. // Save state
  1398. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1399. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1400. // Change state
  1401. gl.enable(gl.SCISSOR_TEST);
  1402. gl.scissor(x, y, width, height);
  1403. // Clear
  1404. this.clear(clearColor, true, true, true);
  1405. // Restore state
  1406. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1407. if (curScissor === true) {
  1408. gl.enable(gl.SCISSOR_TEST);
  1409. } else {
  1410. gl.disable(gl.SCISSOR_TEST);
  1411. }
  1412. }
  1413. /**
  1414. * Set the WebGL's viewport
  1415. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1416. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1417. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1418. */
  1419. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1420. var width = requiredWidth || this.getRenderWidth();
  1421. var height = requiredHeight || this.getRenderHeight();
  1422. var x = viewport.x || 0;
  1423. var y = viewport.y || 0;
  1424. this._cachedViewport = viewport;
  1425. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1426. }
  1427. /**
  1428. * Directly set the WebGL Viewport
  1429. * The x, y, width & height are directly passed to the WebGL call
  1430. * @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.
  1431. */
  1432. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1433. let currentViewport = this._cachedViewport;
  1434. this._cachedViewport = null;
  1435. this._gl.viewport(x, y, width, height);
  1436. return currentViewport;
  1437. }
  1438. public beginFrame(): void {
  1439. this.onBeginFrameObservable.notifyObservers(this);
  1440. this._measureFps();
  1441. }
  1442. public endFrame(): void {
  1443. //force a flush in case we are using a bad OS.
  1444. if (this._badOS) {
  1445. this.flushFramebuffer();
  1446. }
  1447. //submit frame to the vr device, if enabled
  1448. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1449. // TODO: We should only submit the frame if we read frameData successfully.
  1450. this._vrDisplay.submitFrame();
  1451. }
  1452. this.onEndFrameObservable.notifyObservers(this);
  1453. }
  1454. /**
  1455. * resize the view according to the canvas' size.
  1456. * @example
  1457. * window.addEventListener("resize", function () {
  1458. * engine.resize();
  1459. * });
  1460. */
  1461. public resize(): void {
  1462. // We're not resizing the size of the canvas while in VR mode & presenting
  1463. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1464. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1465. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1466. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1467. }
  1468. }
  1469. /**
  1470. * force a specific size of the canvas
  1471. * @param {number} width - the new canvas' width
  1472. * @param {number} height - the new canvas' height
  1473. */
  1474. public setSize(width: number, height: number): void {
  1475. if (!this._renderingCanvas) {
  1476. return;
  1477. }
  1478. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1479. return;
  1480. }
  1481. this._renderingCanvas.width = width;
  1482. this._renderingCanvas.height = height;
  1483. for (var index = 0; index < this.scenes.length; index++) {
  1484. var scene = this.scenes[index];
  1485. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1486. var cam = scene.cameras[camIndex];
  1487. cam._currentRenderId = 0;
  1488. }
  1489. }
  1490. if (this.onResizeObservable.hasObservers) {
  1491. this.onResizeObservable.notifyObservers(this);
  1492. }
  1493. }
  1494. // WebVR functions
  1495. public isVRDevicePresent(): boolean {
  1496. return !!this._vrDisplay;
  1497. }
  1498. public getVRDevice(): any {
  1499. return this._vrDisplay;
  1500. }
  1501. /**
  1502. * Initializes a webVR display and starts listening to display change events.
  1503. * The onVRDisplayChangedObservable will be notified upon these changes.
  1504. * @returns The onVRDisplayChangedObservable.
  1505. */
  1506. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1507. this.initWebVRAsync();
  1508. return this.onVRDisplayChangedObservable;
  1509. }
  1510. /**
  1511. * Initializes a webVR display and starts listening to display change events.
  1512. * The onVRDisplayChangedObservable will be notified upon these changes.
  1513. * @returns A promise containing a VRDisplay and if vr is supported.
  1514. */
  1515. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1516. var notifyObservers = () => {
  1517. var eventArgs = {
  1518. vrDisplay: this._vrDisplay,
  1519. vrSupported: this._vrSupported
  1520. };
  1521. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1522. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1523. }
  1524. if (!this._onVrDisplayConnect) {
  1525. this._onVrDisplayConnect = (event) => {
  1526. this._vrDisplay = event.display;
  1527. notifyObservers();
  1528. };
  1529. this._onVrDisplayDisconnect = () => {
  1530. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1531. this._vrDisplay = undefined;
  1532. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1533. notifyObservers();
  1534. };
  1535. this._onVrDisplayPresentChange = () => {
  1536. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1537. }
  1538. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1539. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1540. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1541. }
  1542. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1543. this._webVRInitPromise.then(notifyObservers);
  1544. return this._webVRInitPromise;
  1545. }
  1546. public enableVR() {
  1547. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1548. var onResolved = () => {
  1549. this.onVRRequestPresentComplete.notifyObservers(true);
  1550. this._onVRFullScreenTriggered();
  1551. };
  1552. var onRejected = () => {
  1553. this.onVRRequestPresentComplete.notifyObservers(false);
  1554. };
  1555. this.onVRRequestPresentStart.notifyObservers(this);
  1556. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  1557. }
  1558. }
  1559. public disableVR() {
  1560. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1561. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  1562. }
  1563. }
  1564. private _onVRFullScreenTriggered = () => {
  1565. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1566. //get the old size before we change
  1567. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  1568. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1569. //get the width and height, change the render size
  1570. var leftEye = this._vrDisplay.getEyeParameters('left');
  1571. this.setHardwareScalingLevel(1);
  1572. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1573. } else {
  1574. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1575. this.setSize(this._oldSize.width, this._oldSize.height);
  1576. }
  1577. }
  1578. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  1579. return new Promise((res, rej)=>{
  1580. if (navigator.getVRDisplays) {
  1581. navigator.getVRDisplays().then((devices: Array<any>)=>{
  1582. this._vrSupported = true;
  1583. // note that devices may actually be an empty array. This is fine;
  1584. // we expect this._vrDisplay to be undefined in this case.
  1585. this._vrDisplay = devices[0];
  1586. res({
  1587. vrDisplay: this._vrDisplay,
  1588. vrSupported: this._vrSupported
  1589. });
  1590. });
  1591. } else {
  1592. this._vrDisplay = undefined;
  1593. this._vrSupported = false;
  1594. res({
  1595. vrDisplay: this._vrDisplay,
  1596. vrSupported: this._vrSupported
  1597. });
  1598. }
  1599. });
  1600. }
  1601. /**
  1602. * Binds the frame buffer to the specified texture.
  1603. * @param texture The texture to render to or null for the default canvas
  1604. * @param faceIndex The face of the texture to render to in case of cube texture
  1605. * @param requiredWidth The width of the target to render to
  1606. * @param requiredHeight The height of the target to render to
  1607. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1608. * @param depthStencilTexture The depth stencil texture to use to render
  1609. */
  1610. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture): void {
  1611. if (this._currentRenderTarget) {
  1612. this.unBindFramebuffer(this._currentRenderTarget);
  1613. }
  1614. this._currentRenderTarget = texture;
  1615. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1616. var gl = this._gl;
  1617. if (texture.isCube) {
  1618. if (faceIndex === undefined) {
  1619. faceIndex = 0;
  1620. }
  1621. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1622. if (depthStencilTexture) {
  1623. if (depthStencilTexture._generateStencilBuffer) {
  1624. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  1625. }
  1626. else {
  1627. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  1628. }
  1629. }
  1630. }
  1631. if (this._cachedViewport && !forceFullscreenViewport) {
  1632. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1633. } else {
  1634. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1635. }
  1636. this.wipeCaches();
  1637. }
  1638. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1639. if (this._currentFramebuffer !== framebuffer) {
  1640. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1641. this._currentFramebuffer = framebuffer;
  1642. }
  1643. }
  1644. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1645. this._currentRenderTarget = null;
  1646. // If MSAA, we need to bitblt back to main texture
  1647. var gl = this._gl;
  1648. if (texture._MSAAFramebuffer) {
  1649. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1650. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1651. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1652. 0, 0, texture.width, texture.height,
  1653. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1654. }
  1655. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1656. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1657. gl.generateMipmap(gl.TEXTURE_2D);
  1658. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1659. }
  1660. if (onBeforeUnbind) {
  1661. if (texture._MSAAFramebuffer) {
  1662. // Bind the correct framebuffer
  1663. this.bindUnboundFramebuffer(texture._framebuffer);
  1664. }
  1665. onBeforeUnbind();
  1666. }
  1667. this.bindUnboundFramebuffer(null);
  1668. }
  1669. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1670. this._currentRenderTarget = null;
  1671. // If MSAA, we need to bitblt back to main texture
  1672. var gl = this._gl;
  1673. if (textures[0]._MSAAFramebuffer) {
  1674. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  1675. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  1676. var attachments = textures[0]._attachments;
  1677. if (!attachments) {
  1678. attachments = new Array(textures.length);
  1679. textures[0]._attachments = attachments;
  1680. }
  1681. for (var i = 0; i < textures.length; i++) {
  1682. var texture = textures[i];
  1683. for (var j = 0; j < attachments.length; j++) {
  1684. attachments[j] = gl.NONE;
  1685. }
  1686. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1687. gl.readBuffer(attachments[i]);
  1688. gl.drawBuffers(attachments);
  1689. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1690. 0, 0, texture.width, texture.height,
  1691. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1692. }
  1693. for (var i = 0; i < attachments.length; i++) {
  1694. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  1695. }
  1696. gl.drawBuffers(attachments);
  1697. }
  1698. for (var i = 0; i < textures.length; i++) {
  1699. var texture = textures[i];
  1700. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1701. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1702. gl.generateMipmap(gl.TEXTURE_2D);
  1703. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1704. }
  1705. }
  1706. if (onBeforeUnbind) {
  1707. if (textures[0]._MSAAFramebuffer) {
  1708. // Bind the correct framebuffer
  1709. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  1710. }
  1711. onBeforeUnbind();
  1712. }
  1713. this.bindUnboundFramebuffer(null);
  1714. }
  1715. public generateMipMapsForCubemap(texture: InternalTexture) {
  1716. if (texture.generateMipMaps) {
  1717. var gl = this._gl;
  1718. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  1719. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1720. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1721. }
  1722. }
  1723. public flushFramebuffer(): void {
  1724. this._gl.flush();
  1725. }
  1726. public restoreDefaultFramebuffer(): void {
  1727. if (this._currentRenderTarget) {
  1728. this.unBindFramebuffer(this._currentRenderTarget);
  1729. } else {
  1730. this.bindUnboundFramebuffer(null);
  1731. }
  1732. if (this._cachedViewport) {
  1733. this.setViewport(this._cachedViewport);
  1734. }
  1735. this.wipeCaches();
  1736. }
  1737. // UBOs
  1738. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  1739. var ubo = this._gl.createBuffer();
  1740. if (!ubo) {
  1741. throw new Error("Unable to create uniform buffer");
  1742. }
  1743. this.bindUniformBuffer(ubo);
  1744. if (elements instanceof Float32Array) {
  1745. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1746. } else {
  1747. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1748. }
  1749. this.bindUniformBuffer(null);
  1750. ubo.references = 1;
  1751. return ubo;
  1752. }
  1753. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  1754. var ubo = this._gl.createBuffer();
  1755. if (!ubo) {
  1756. throw new Error("Unable to create dynamic uniform buffer");
  1757. }
  1758. this.bindUniformBuffer(ubo);
  1759. if (elements instanceof Float32Array) {
  1760. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1761. } else {
  1762. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1763. }
  1764. this.bindUniformBuffer(null);
  1765. ubo.references = 1;
  1766. return ubo;
  1767. }
  1768. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  1769. this.bindUniformBuffer(uniformBuffer);
  1770. if (offset === undefined) {
  1771. offset = 0;
  1772. }
  1773. if (count === undefined) {
  1774. if (elements instanceof Float32Array) {
  1775. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1776. } else {
  1777. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1778. }
  1779. } else {
  1780. if (elements instanceof Float32Array) {
  1781. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1782. } else {
  1783. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1784. }
  1785. }
  1786. this.bindUniformBuffer(null);
  1787. }
  1788. // VBOs
  1789. private _resetVertexBufferBinding(): void {
  1790. this.bindArrayBuffer(null);
  1791. this._cachedVertexBuffers = null;
  1792. }
  1793. public createVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1794. var vbo = this._gl.createBuffer();
  1795. if (!vbo) {
  1796. throw new Error("Unable to create vertex buffer");
  1797. }
  1798. this.bindArrayBuffer(vbo);
  1799. if (vertices instanceof Float32Array) {
  1800. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1801. } else {
  1802. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1803. }
  1804. this._resetVertexBufferBinding();
  1805. vbo.references = 1;
  1806. return vbo;
  1807. }
  1808. public createDynamicVertexBuffer(vertices: FloatArray): WebGLBuffer {
  1809. var vbo = this._gl.createBuffer();
  1810. if (!vbo) {
  1811. throw new Error("Unable to create dynamic vertex buffer");
  1812. }
  1813. this.bindArrayBuffer(vbo);
  1814. if (vertices instanceof Float32Array) {
  1815. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1816. } else {
  1817. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1818. }
  1819. this._resetVertexBufferBinding();
  1820. vbo.references = 1;
  1821. return vbo;
  1822. }
  1823. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  1824. // Force cache update
  1825. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  1826. this.bindIndexBuffer(indexBuffer);
  1827. var arrayBuffer;
  1828. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  1829. arrayBuffer = indices;
  1830. } else {
  1831. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1832. }
  1833. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  1834. this._resetIndexBufferBinding();
  1835. }
  1836. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: FloatArray, offset?: number, count?: number): void {
  1837. this.bindArrayBuffer(vertexBuffer);
  1838. if (offset === undefined) {
  1839. offset = 0;
  1840. }
  1841. if (count === undefined) {
  1842. if (vertices instanceof Float32Array) {
  1843. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1844. } else {
  1845. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1846. }
  1847. } else {
  1848. if (vertices instanceof Float32Array) {
  1849. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1850. } else {
  1851. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1852. }
  1853. }
  1854. this._resetVertexBufferBinding();
  1855. }
  1856. private _resetIndexBufferBinding(): void {
  1857. this.bindIndexBuffer(null);
  1858. this._cachedIndexBuffer = null;
  1859. }
  1860. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  1861. var vbo = this._gl.createBuffer();
  1862. if (!vbo) {
  1863. throw new Error("Unable to create index buffer");
  1864. }
  1865. this.bindIndexBuffer(vbo);
  1866. // Check for 32 bits indices
  1867. var arrayBuffer;
  1868. var need32Bits = false;
  1869. if (indices instanceof Uint16Array) {
  1870. arrayBuffer = indices;
  1871. } else {
  1872. //check 32 bit support
  1873. if (this._caps.uintIndices) {
  1874. if (indices instanceof Uint32Array) {
  1875. arrayBuffer = indices;
  1876. need32Bits = true;
  1877. } else {
  1878. //number[] or Int32Array, check if 32 bit is necessary
  1879. for (var index = 0; index < indices.length; index++) {
  1880. if (indices[index] > 65535) {
  1881. need32Bits = true;
  1882. break;
  1883. }
  1884. }
  1885. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1886. }
  1887. } else {
  1888. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1889. arrayBuffer = new Uint16Array(indices);
  1890. }
  1891. }
  1892. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1893. this._resetIndexBufferBinding();
  1894. vbo.references = 1;
  1895. vbo.is32Bits = need32Bits;
  1896. return vbo;
  1897. }
  1898. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  1899. if (!this._vaoRecordInProgress) {
  1900. this._unbindVertexArrayObject();
  1901. }
  1902. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1903. }
  1904. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  1905. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1906. }
  1907. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1908. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1909. }
  1910. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1911. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1912. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1913. };
  1914. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  1915. if (!this._vaoRecordInProgress) {
  1916. this._unbindVertexArrayObject();
  1917. }
  1918. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1919. }
  1920. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  1921. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1922. this._gl.bindBuffer(target, buffer);
  1923. this._currentBoundBuffer[target] = buffer;
  1924. }
  1925. }
  1926. public updateArrayBuffer(data: Float32Array): void {
  1927. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1928. }
  1929. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1930. var pointer = this._currentBufferPointers[indx];
  1931. var changed = false;
  1932. if (!pointer.active) {
  1933. changed = true;
  1934. pointer.active = true;
  1935. pointer.index = indx;
  1936. pointer.size = size;
  1937. pointer.type = type;
  1938. pointer.normalized = normalized;
  1939. pointer.stride = stride;
  1940. pointer.offset = offset;
  1941. pointer.buffer = buffer;
  1942. } else {
  1943. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1944. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1945. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1946. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1947. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1948. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1949. }
  1950. if (changed || this._vaoRecordInProgress) {
  1951. this.bindArrayBuffer(buffer);
  1952. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1953. }
  1954. }
  1955. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  1956. if (indexBuffer == null) {
  1957. return;
  1958. }
  1959. if (this._cachedIndexBuffer !== indexBuffer) {
  1960. this._cachedIndexBuffer = indexBuffer;
  1961. this.bindIndexBuffer(indexBuffer);
  1962. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1963. }
  1964. }
  1965. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1966. var attributes = effect.getAttributesNames();
  1967. if (!this._vaoRecordInProgress) {
  1968. this._unbindVertexArrayObject();
  1969. }
  1970. this.unbindAllAttributes();
  1971. for (var index = 0; index < attributes.length; index++) {
  1972. var order = effect.getAttributeLocation(index);
  1973. if (order >= 0) {
  1974. var vertexBuffer = vertexBuffers[attributes[index]];
  1975. if (!vertexBuffer) {
  1976. continue;
  1977. }
  1978. this._gl.enableVertexAttribArray(order);
  1979. if (!this._vaoRecordInProgress) {
  1980. this._vertexAttribArraysEnabled[order] = true;
  1981. }
  1982. var buffer = vertexBuffer.getBuffer();
  1983. if (buffer) {
  1984. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1985. if (vertexBuffer.getIsInstanced()) {
  1986. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1987. if (!this._vaoRecordInProgress) {
  1988. this._currentInstanceLocations.push(order);
  1989. this._currentInstanceBuffers.push(buffer);
  1990. }
  1991. }
  1992. }
  1993. }
  1994. }
  1995. }
  1996. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  1997. var vao = this._gl.createVertexArray();
  1998. this._vaoRecordInProgress = true;
  1999. this._gl.bindVertexArray(vao);
  2000. this._mustWipeVertexAttributes = true;
  2001. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2002. this.bindIndexBuffer(indexBuffer);
  2003. this._vaoRecordInProgress = false;
  2004. this._gl.bindVertexArray(null);
  2005. return vao;
  2006. }
  2007. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2008. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2009. this._cachedVertexArrayObject = vertexArrayObject;
  2010. this._gl.bindVertexArray(vertexArrayObject);
  2011. this._cachedVertexBuffers = null;
  2012. this._cachedIndexBuffer = null;
  2013. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2014. this._mustWipeVertexAttributes = true;
  2015. }
  2016. }
  2017. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2018. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2019. this._cachedVertexBuffers = vertexBuffer;
  2020. this._cachedEffectForVertexBuffers = effect;
  2021. let attributesCount = effect.getAttributesCount();
  2022. this._unbindVertexArrayObject();
  2023. this.unbindAllAttributes();
  2024. var offset = 0;
  2025. for (var index = 0; index < attributesCount; index++) {
  2026. if (index < vertexDeclaration.length) {
  2027. var order = effect.getAttributeLocation(index);
  2028. if (order >= 0) {
  2029. this._gl.enableVertexAttribArray(order);
  2030. this._vertexAttribArraysEnabled[order] = true;
  2031. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2032. }
  2033. offset += vertexDeclaration[index] * 4;
  2034. }
  2035. }
  2036. }
  2037. this._bindIndexBufferWithCache(indexBuffer);
  2038. }
  2039. private _unbindVertexArrayObject(): void {
  2040. if (!this._cachedVertexArrayObject) {
  2041. return;
  2042. }
  2043. this._cachedVertexArrayObject = null;
  2044. this._gl.bindVertexArray(null);
  2045. }
  2046. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2047. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2048. this._cachedVertexBuffers = vertexBuffers;
  2049. this._cachedEffectForVertexBuffers = effect;
  2050. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2051. }
  2052. this._bindIndexBufferWithCache(indexBuffer);
  2053. }
  2054. public unbindInstanceAttributes() {
  2055. var boundBuffer;
  2056. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2057. var instancesBuffer = this._currentInstanceBuffers[i];
  2058. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2059. boundBuffer = instancesBuffer;
  2060. this.bindArrayBuffer(instancesBuffer);
  2061. }
  2062. var offsetLocation = this._currentInstanceLocations[i];
  2063. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2064. }
  2065. this._currentInstanceBuffers.length = 0;
  2066. this._currentInstanceLocations.length = 0;
  2067. }
  2068. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2069. this._gl.deleteVertexArray(vao);
  2070. }
  2071. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2072. buffer.references--;
  2073. if (buffer.references === 0) {
  2074. this._gl.deleteBuffer(buffer);
  2075. return true;
  2076. }
  2077. return false;
  2078. }
  2079. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2080. var buffer = this._gl.createBuffer();
  2081. if (!buffer) {
  2082. throw new Error("Unable to create instance buffer");
  2083. }
  2084. buffer.capacity = capacity;
  2085. this.bindArrayBuffer(buffer);
  2086. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2087. return buffer;
  2088. }
  2089. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2090. this._gl.deleteBuffer(buffer);
  2091. }
  2092. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2093. this.bindArrayBuffer(instancesBuffer);
  2094. if (data) {
  2095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2096. }
  2097. if ((<any>offsetLocations[0]).index !== undefined) {
  2098. let stride = 0;
  2099. for (let i = 0; i < offsetLocations.length; i++) {
  2100. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2101. stride += ai.attributeSize * 4;
  2102. }
  2103. for (let i = 0; i < offsetLocations.length; i++) {
  2104. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2105. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2106. this._gl.enableVertexAttribArray(ai.index);
  2107. this._vertexAttribArraysEnabled[ai.index] = true;
  2108. }
  2109. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2110. this._gl.vertexAttribDivisor(ai.index, 1);
  2111. this._currentInstanceLocations.push(ai.index);
  2112. this._currentInstanceBuffers.push(instancesBuffer);
  2113. }
  2114. } else {
  2115. for (let index = 0; index < 4; index++) {
  2116. let offsetLocation = <number>offsetLocations[index];
  2117. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2118. this._gl.enableVertexAttribArray(offsetLocation);
  2119. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2120. }
  2121. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2122. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2123. this._currentInstanceLocations.push(offsetLocation);
  2124. this._currentInstanceBuffers.push(instancesBuffer);
  2125. }
  2126. }
  2127. }
  2128. public applyStates() {
  2129. this._depthCullingState.apply(this._gl);
  2130. this._stencilState.apply(this._gl);
  2131. this._alphaState.apply(this._gl);
  2132. }
  2133. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2134. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2135. }
  2136. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2137. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2138. }
  2139. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2140. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2141. }
  2142. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2143. // Apply states
  2144. this.applyStates();
  2145. this._drawCalls.addCount(1, false);
  2146. // Render
  2147. const drawMode = this.DrawMode(fillMode);
  2148. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2149. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2150. if (instancesCount) {
  2151. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2152. } else {
  2153. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2154. }
  2155. }
  2156. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2157. // Apply states
  2158. this.applyStates();
  2159. this._drawCalls.addCount(1, false);
  2160. const drawMode = this.DrawMode(fillMode);
  2161. if (instancesCount) {
  2162. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2163. } else {
  2164. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2165. }
  2166. }
  2167. private DrawMode(fillMode: number): number {
  2168. switch (fillMode) {
  2169. // Triangle views
  2170. case Material.TriangleFillMode:
  2171. return this._gl.TRIANGLES;
  2172. case Material.PointFillMode:
  2173. return this._gl.POINTS;
  2174. case Material.WireFrameFillMode:
  2175. return this._gl.LINES;
  2176. // Draw modes
  2177. case Material.PointListDrawMode:
  2178. return this._gl.POINTS
  2179. case Material.LineListDrawMode:
  2180. return this._gl.LINES;
  2181. case Material.LineLoopDrawMode:
  2182. return this._gl.LINE_LOOP
  2183. case Material.LineStripDrawMode:
  2184. return this._gl.LINE_STRIP
  2185. case Material.TriangleStripDrawMode:
  2186. return this._gl.TRIANGLE_STRIP
  2187. case Material.TriangleFanDrawMode:
  2188. return this._gl.TRIANGLE_FAN;
  2189. default:
  2190. return this._gl.TRIANGLES;
  2191. }
  2192. }
  2193. // Shaders
  2194. public _releaseEffect(effect: Effect): void {
  2195. if (this._compiledEffects[effect._key]) {
  2196. delete this._compiledEffects[effect._key];
  2197. this._deleteProgram(effect.getProgram());
  2198. }
  2199. }
  2200. public _deleteProgram(program: WebGLProgram): void {
  2201. if (program) {
  2202. program.__SPECTOR_rebuildProgram = null;
  2203. if (program.transformFeedback) {
  2204. this.deleteTransformFeedback(program.transformFeedback);
  2205. program.transformFeedback = null;
  2206. }
  2207. this._gl.deleteProgram(program);
  2208. }
  2209. }
  2210. /**
  2211. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2212. * @param samplers An array of string used to represent textures
  2213. */
  2214. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2215. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2216. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2217. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2218. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2219. if (this._compiledEffects[name]) {
  2220. var compiledEffect = <Effect>this._compiledEffects[name];
  2221. if (onCompiled && compiledEffect.isReady()) {
  2222. onCompiled(compiledEffect);
  2223. }
  2224. return compiledEffect;
  2225. }
  2226. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2227. effect._key = name;
  2228. this._compiledEffects[name] = effect;
  2229. return effect;
  2230. }
  2231. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2232. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2233. return this.createEffect(
  2234. {
  2235. vertex: "particles",
  2236. fragmentElement: fragmentName
  2237. },
  2238. ["position", "color", "options"],
  2239. ["view", "projection"].concat(uniformsNames),
  2240. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2241. }
  2242. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2243. context = context || this._gl;
  2244. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2245. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2246. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2247. }
  2248. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2249. context = context || this._gl;
  2250. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2251. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2252. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2253. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2254. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2255. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2256. return program;
  2257. }
  2258. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2259. var shaderProgram = context.createProgram();
  2260. if (!shaderProgram) {
  2261. throw new Error("Unable to create program");
  2262. }
  2263. context.attachShader(shaderProgram, vertexShader);
  2264. context.attachShader(shaderProgram, fragmentShader);
  2265. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2266. let transformFeedback = this.createTransformFeedback();
  2267. this.bindTransformFeedback(transformFeedback);
  2268. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2269. shaderProgram.transformFeedback = transformFeedback;
  2270. }
  2271. context.linkProgram(shaderProgram);
  2272. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2273. this.bindTransformFeedback(null);
  2274. }
  2275. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2276. if (!linked) {
  2277. context.validateProgram(shaderProgram);
  2278. var error = context.getProgramInfoLog(shaderProgram);
  2279. if (error) {
  2280. throw new Error(error);
  2281. }
  2282. }
  2283. context.deleteShader(vertexShader);
  2284. context.deleteShader(fragmentShader);
  2285. return shaderProgram;
  2286. }
  2287. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2288. var results = new Array<Nullable<WebGLUniformLocation>>();
  2289. for (var index = 0; index < uniformsNames.length; index++) {
  2290. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2291. }
  2292. return results;
  2293. }
  2294. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2295. var results = [];
  2296. for (var index = 0; index < attributesNames.length; index++) {
  2297. try {
  2298. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2299. } catch (e) {
  2300. results.push(-1);
  2301. }
  2302. }
  2303. return results;
  2304. }
  2305. public enableEffect(effect: Nullable<Effect>): void {
  2306. if (!effect) {
  2307. return;
  2308. }
  2309. // Use program
  2310. this.bindSamplers(effect);
  2311. this._currentEffect = effect;
  2312. if (effect.onBind) {
  2313. effect.onBind(effect);
  2314. }
  2315. effect.onBindObservable.notifyObservers(effect);
  2316. }
  2317. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2318. if (!uniform)
  2319. return;
  2320. this._gl.uniform1iv(uniform, array);
  2321. }
  2322. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2323. if (!uniform || array.length % 2 !== 0)
  2324. return;
  2325. this._gl.uniform2iv(uniform, array);
  2326. }
  2327. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2328. if (!uniform || array.length % 3 !== 0)
  2329. return;
  2330. this._gl.uniform3iv(uniform, array);
  2331. }
  2332. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2333. if (!uniform || array.length % 4 !== 0)
  2334. return;
  2335. this._gl.uniform4iv(uniform, array);
  2336. }
  2337. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2338. if (!uniform)
  2339. return;
  2340. this._gl.uniform1fv(uniform, array);
  2341. }
  2342. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2343. if (!uniform || array.length % 2 !== 0)
  2344. return;
  2345. this._gl.uniform2fv(uniform, array);
  2346. }
  2347. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2348. if (!uniform || array.length % 3 !== 0)
  2349. return;
  2350. this._gl.uniform3fv(uniform, array);
  2351. }
  2352. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  2353. if (!uniform || array.length % 4 !== 0)
  2354. return;
  2355. this._gl.uniform4fv(uniform, array);
  2356. }
  2357. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2358. if (!uniform)
  2359. return;
  2360. this._gl.uniform1fv(uniform, <any>array);
  2361. }
  2362. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2363. if (!uniform || array.length % 2 !== 0)
  2364. return;
  2365. this._gl.uniform2fv(uniform, <any>array);
  2366. }
  2367. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2368. if (!uniform || array.length % 3 !== 0)
  2369. return;
  2370. this._gl.uniform3fv(uniform, <any>array);
  2371. }
  2372. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  2373. if (!uniform || array.length % 4 !== 0)
  2374. return;
  2375. this._gl.uniform4fv(uniform, <any>array);
  2376. }
  2377. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2378. if (!uniform)
  2379. return;
  2380. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2381. }
  2382. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  2383. if (!uniform)
  2384. return;
  2385. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  2386. }
  2387. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2388. if (!uniform)
  2389. return;
  2390. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2391. }
  2392. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2393. if (!uniform)
  2394. return;
  2395. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2396. }
  2397. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2398. if (!uniform)
  2399. return;
  2400. this._gl.uniform1i(uniform, value);
  2401. }
  2402. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2403. if (!uniform)
  2404. return;
  2405. this._gl.uniform1f(uniform, value);
  2406. }
  2407. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2408. if (!uniform)
  2409. return;
  2410. this._gl.uniform2f(uniform, x, y);
  2411. }
  2412. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2413. if (!uniform)
  2414. return;
  2415. this._gl.uniform3f(uniform, x, y, z);
  2416. }
  2417. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  2418. if (!uniform)
  2419. return;
  2420. this._gl.uniform1i(uniform, bool);
  2421. }
  2422. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2423. if (!uniform)
  2424. return;
  2425. this._gl.uniform4f(uniform, x, y, z, w);
  2426. }
  2427. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  2428. if (!uniform)
  2429. return;
  2430. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2431. }
  2432. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  2433. if (!uniform)
  2434. return;
  2435. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2436. }
  2437. /**
  2438. * Sets a Color4 on a uniform variable
  2439. * @param uniform defines the uniform location
  2440. * @param color4 defines the value to be set
  2441. */
  2442. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  2443. if (!uniform)
  2444. return;
  2445. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  2446. }
  2447. // States
  2448. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2449. // Culling
  2450. if (this._depthCullingState.cull !== culling || force) {
  2451. this._depthCullingState.cull = culling;
  2452. }
  2453. // Cull face
  2454. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2455. if (this._depthCullingState.cullFace !== cullFace || force) {
  2456. this._depthCullingState.cullFace = cullFace;
  2457. }
  2458. // Z offset
  2459. this.setZOffset(zOffset);
  2460. // Front face
  2461. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2462. if (this._depthCullingState.frontFace !== frontFace || force) {
  2463. this._depthCullingState.frontFace = frontFace;
  2464. }
  2465. }
  2466. public setZOffset(value: number): void {
  2467. this._depthCullingState.zOffset = value;
  2468. }
  2469. public getZOffset(): number {
  2470. return this._depthCullingState.zOffset;
  2471. }
  2472. public setDepthBuffer(enable: boolean): void {
  2473. this._depthCullingState.depthTest = enable;
  2474. }
  2475. public getDepthWrite(): boolean {
  2476. return this._depthCullingState.depthMask;
  2477. }
  2478. public setDepthWrite(enable: boolean): void {
  2479. this._depthCullingState.depthMask = enable;
  2480. }
  2481. public setColorWrite(enable: boolean): void {
  2482. this._gl.colorMask(enable, enable, enable, enable);
  2483. this._colorWrite = enable;
  2484. }
  2485. public getColorWrite(): boolean {
  2486. return this._colorWrite;
  2487. }
  2488. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2489. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2490. }
  2491. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2492. if (this._alphaMode === mode) {
  2493. return;
  2494. }
  2495. switch (mode) {
  2496. case Engine.ALPHA_DISABLE:
  2497. this._alphaState.alphaBlend = false;
  2498. break;
  2499. case Engine.ALPHA_PREMULTIPLIED:
  2500. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2501. this._alphaState.alphaBlend = true;
  2502. break;
  2503. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2504. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2505. this._alphaState.alphaBlend = true;
  2506. break;
  2507. case Engine.ALPHA_COMBINE:
  2508. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2509. this._alphaState.alphaBlend = true;
  2510. break;
  2511. case Engine.ALPHA_ONEONE:
  2512. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2513. this._alphaState.alphaBlend = true;
  2514. break;
  2515. case Engine.ALPHA_ADD:
  2516. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2517. this._alphaState.alphaBlend = true;
  2518. break;
  2519. case Engine.ALPHA_SUBTRACT:
  2520. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2521. this._alphaState.alphaBlend = true;
  2522. break;
  2523. case Engine.ALPHA_MULTIPLY:
  2524. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2525. this._alphaState.alphaBlend = true;
  2526. break;
  2527. case Engine.ALPHA_MAXIMIZED:
  2528. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2529. this._alphaState.alphaBlend = true;
  2530. break;
  2531. case Engine.ALPHA_INTERPOLATE:
  2532. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2533. this._alphaState.alphaBlend = true;
  2534. break;
  2535. case Engine.ALPHA_SCREENMODE:
  2536. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2537. this._alphaState.alphaBlend = true;
  2538. break;
  2539. }
  2540. if (!noDepthWriteChange) {
  2541. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2542. }
  2543. this._alphaMode = mode;
  2544. }
  2545. public getAlphaMode(): number {
  2546. return this._alphaMode;
  2547. }
  2548. // Textures
  2549. public wipeCaches(bruteForce?: boolean): void {
  2550. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2551. return;
  2552. }
  2553. this._currentEffect = null;
  2554. // 6/8/2017: deltakosh: Should not be required anymore.
  2555. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  2556. if (bruteForce) {
  2557. this.resetTextureCache();
  2558. this._currentProgram = null;
  2559. this._stencilState.reset();
  2560. this._depthCullingState.reset();
  2561. this.setDepthFunctionToLessOrEqual();
  2562. this._alphaState.reset();
  2563. }
  2564. this._resetVertexBufferBinding();
  2565. this._cachedIndexBuffer = null;
  2566. this._cachedEffectForVertexBuffers = null;
  2567. this._unbindVertexArrayObject();
  2568. this.bindIndexBuffer(null);
  2569. }
  2570. /**
  2571. * Set the compressed texture format to use, based on the formats you have, and the formats
  2572. * supported by the hardware / browser.
  2573. *
  2574. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2575. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2576. * to API arguments needed to compressed textures. This puts the burden on the container
  2577. * generator to house the arcane code for determining these for current & future formats.
  2578. *
  2579. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2580. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2581. *
  2582. * Note: The result of this call is not taken into account when a texture is base64.
  2583. *
  2584. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2585. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2586. *
  2587. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2588. * @returns The extension selected.
  2589. */
  2590. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  2591. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2592. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2593. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2594. return this._textureFormatInUse = this._texturesSupported[i];
  2595. }
  2596. }
  2597. }
  2598. // actively set format to nothing, to allow this to be called more than once
  2599. // and possibly fail the 2nd time
  2600. this._textureFormatInUse = null;
  2601. return null;
  2602. }
  2603. public _createTexture(): WebGLTexture {
  2604. let texture = this._gl.createTexture();
  2605. if (!texture) {
  2606. throw new Error("Unable to create texture");
  2607. }
  2608. return texture;
  2609. }
  2610. /**
  2611. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2612. * @param {string} urlArg- This contains one of the following:
  2613. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2614. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2615. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2616. *
  2617. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2618. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2619. * @param {Scene} scene- Needed for loading to the correct scene.
  2620. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2621. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2622. * @param {callback} onError- Optional callback to be called upon failure.
  2623. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2624. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2625. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2626. *
  2627. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2628. */
  2629. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  2630. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2631. buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  2632. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2633. var fromData = url.substr(0, 5) === "data:";
  2634. var fromBlob = url.substr(0, 5) === "blob:";
  2635. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2636. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2637. // establish the file extension, if possible
  2638. var lastDot = url.lastIndexOf('.');
  2639. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2640. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  2641. var isTGA = (extension.indexOf(".tga") === 0);
  2642. // determine if a ktx file should be substituted
  2643. var isKTX = false;
  2644. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2645. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2646. isKTX = true;
  2647. }
  2648. if (scene) {
  2649. scene._addPendingData(texture);
  2650. }
  2651. texture.url = url;
  2652. texture.generateMipMaps = !noMipmap;
  2653. texture.samplingMode = samplingMode;
  2654. texture.invertY = invertY;
  2655. if (!this._doNotHandleContextLost) {
  2656. // Keep a link to the buffer only if we plan to handle context lost
  2657. texture._buffer = buffer;
  2658. }
  2659. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2660. if (onLoad && !fallBack) {
  2661. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2662. }
  2663. if (!fallBack) this._internalTexturesCache.push(texture);
  2664. var onerror = (message?: string, exception?: any) => {
  2665. if (scene) {
  2666. scene._removePendingData(texture);
  2667. }
  2668. if (onLoadObserver) {
  2669. texture.onLoadedObservable.remove(onLoadObserver);
  2670. }
  2671. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2672. if (isKTX) {
  2673. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2674. } else if (Tools.UseFallbackTexture) {
  2675. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2676. }
  2677. if (onError) {
  2678. onError(message || "Unknown error", exception);
  2679. }
  2680. };
  2681. var callback: Nullable<(arrayBuffer: any) => void> = null;
  2682. // processing for non-image formats
  2683. if (isKTX || isTGA || isDDS) {
  2684. if (isKTX) {
  2685. callback = (data) => {
  2686. var ktx = new KhronosTextureContainer(data, 1);
  2687. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2688. ktx.uploadLevels(this._gl, !noMipmap);
  2689. return false;
  2690. }, samplingMode);
  2691. };
  2692. } else if (isTGA) {
  2693. callback = (arrayBuffer) => {
  2694. var data = new Uint8Array(arrayBuffer);
  2695. var header = TGATools.GetTGAHeader(data);
  2696. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2697. TGATools.UploadContent(this._gl, data);
  2698. return false;
  2699. }, samplingMode);
  2700. };
  2701. } else if (isDDS) {
  2702. callback = (data) => {
  2703. var info = DDSTools.GetDDSInfo(data);
  2704. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2705. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2706. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2707. return false;
  2708. }, samplingMode);
  2709. };
  2710. }
  2711. if (!buffer) {
  2712. this._loadFile(url, data => {
  2713. if (callback) {
  2714. callback(data);
  2715. }
  2716. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  2717. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  2718. });
  2719. } else {
  2720. if (callback) {
  2721. callback(buffer);
  2722. }
  2723. }
  2724. // image format processing
  2725. } else {
  2726. var onload = (img: HTMLImageElement) => {
  2727. if (fromBlob && !this._doNotHandleContextLost) {
  2728. // We need to store the image if we need to rebuild the texture
  2729. // in case of a webgl context lost
  2730. texture._buffer = img;
  2731. }
  2732. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2733. let gl = this._gl;
  2734. var isPot = (img.width === potWidth && img.height === potHeight);
  2735. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2736. if (isPot) {
  2737. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2738. return false;
  2739. }
  2740. // Using shaders to rescale because canvas.drawImage is lossy
  2741. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2742. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2743. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2748. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2749. this._releaseTexture(source);
  2750. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2751. continuationCallback();
  2752. });
  2753. return true;
  2754. }, samplingMode);
  2755. };
  2756. if (!fromData || isBase64)
  2757. if (buffer instanceof HTMLImageElement) {
  2758. onload(buffer);
  2759. } else {
  2760. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2761. }
  2762. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  2763. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2764. else
  2765. onload(<HTMLImageElement>buffer);
  2766. }
  2767. return texture;
  2768. }
  2769. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  2770. let rtt = this.createRenderTargetTexture({
  2771. width: destination.width,
  2772. height: destination.height,
  2773. }, {
  2774. generateMipMaps: false,
  2775. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2776. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2777. generateDepthBuffer: false,
  2778. generateStencilBuffer: false
  2779. }
  2780. );
  2781. if (!this._rescalePostProcess) {
  2782. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2783. }
  2784. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2785. this._rescalePostProcess.onApply = function (effect) {
  2786. effect._bindTexture("textureSampler", source);
  2787. }
  2788. let hostingScene = scene;
  2789. if (!hostingScene) {
  2790. hostingScene = this.scenes[this.scenes.length - 1];
  2791. }
  2792. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  2793. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  2794. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2795. this.unBindFramebuffer(rtt);
  2796. this._releaseTexture(rtt);
  2797. if (onComplete) {
  2798. onComplete();
  2799. }
  2800. });
  2801. }
  2802. private _getInternalFormat(format: number): number {
  2803. var internalFormat = this._gl.RGBA;
  2804. switch (format) {
  2805. case Engine.TEXTUREFORMAT_ALPHA:
  2806. internalFormat = this._gl.ALPHA;
  2807. break;
  2808. case Engine.TEXTUREFORMAT_LUMINANCE:
  2809. internalFormat = this._gl.LUMINANCE;
  2810. break;
  2811. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2812. internalFormat = this._gl.LUMINANCE_ALPHA;
  2813. break;
  2814. case Engine.TEXTUREFORMAT_RGB:
  2815. case Engine.TEXTUREFORMAT_RGB32F:
  2816. internalFormat = this._gl.RGB;
  2817. break;
  2818. case Engine.TEXTUREFORMAT_RGBA:
  2819. case Engine.TEXTUREFORMAT_RGBA32F:
  2820. internalFormat = this._gl.RGBA;
  2821. break;
  2822. case Engine.TEXTUREFORMAT_R32F:
  2823. internalFormat = this._gl.RED;
  2824. break;
  2825. case Engine.TEXTUREFORMAT_RG32F:
  2826. internalFormat = this._gl.RG;
  2827. break;
  2828. }
  2829. return internalFormat;
  2830. }
  2831. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  2832. if (!texture) {
  2833. return;
  2834. }
  2835. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  2836. var internalFormat = this._getInternalFormat(format);
  2837. var textureType = this._getWebGLTextureType(type);
  2838. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2839. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2840. if (!this._doNotHandleContextLost) {
  2841. texture._bufferView = data;
  2842. texture.format = format;
  2843. texture.type = type;
  2844. texture.invertY = invertY;
  2845. texture._compression = compression;
  2846. }
  2847. if (texture.width % 4 !== 0) {
  2848. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2849. }
  2850. if (compression && data) {
  2851. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, data);
  2852. } else {
  2853. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  2854. }
  2855. if (texture.generateMipMaps) {
  2856. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2857. }
  2858. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2859. // this.resetTextureCache();
  2860. texture.isReady = true;
  2861. }
  2862. 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 {
  2863. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2864. texture.baseWidth = width;
  2865. texture.baseHeight = height;
  2866. texture.width = width;
  2867. texture.height = height;
  2868. texture.format = format;
  2869. texture.generateMipMaps = generateMipMaps;
  2870. texture.samplingMode = samplingMode;
  2871. texture.invertY = invertY;
  2872. texture._compression = compression;
  2873. texture.type = type;
  2874. if (!this._doNotHandleContextLost) {
  2875. texture._bufferView = data;
  2876. }
  2877. this.updateRawTexture(texture, data, format, invertY, compression, type);
  2878. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2879. // Filters
  2880. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2882. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2883. if (generateMipMaps) {
  2884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2885. }
  2886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2887. this._internalTexturesCache.push(texture);
  2888. return texture;
  2889. }
  2890. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2891. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2892. texture.baseWidth = width;
  2893. texture.baseHeight = height;
  2894. if (generateMipMaps) {
  2895. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2896. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2897. }
  2898. // this.resetTextureCache();
  2899. texture.width = width;
  2900. texture.height = height;
  2901. texture.isReady = false;
  2902. texture.generateMipMaps = generateMipMaps;
  2903. texture.samplingMode = samplingMode;
  2904. this.updateTextureSamplingMode(samplingMode, texture);
  2905. this._internalTexturesCache.push(texture);
  2906. return texture;
  2907. }
  2908. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2909. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2910. if (texture.isCube) {
  2911. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  2912. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2913. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2914. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2915. } else if (texture.is3D) {
  2916. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  2917. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2919. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2920. } else {
  2921. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2922. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2923. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2924. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2925. }
  2926. texture.samplingMode = samplingMode;
  2927. }
  2928. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2929. if (!texture) {
  2930. return;
  2931. }
  2932. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2933. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2934. if (premulAlpha) {
  2935. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2936. }
  2937. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2938. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2939. if (texture.generateMipMaps) {
  2940. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2941. }
  2942. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2943. if (premulAlpha) {
  2944. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2945. }
  2946. texture.isReady = true;
  2947. }
  2948. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  2949. if (!texture || texture._isDisabled) {
  2950. return;
  2951. }
  2952. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  2953. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2954. try {
  2955. // Testing video texture support
  2956. if (this._videoTextureSupported === undefined) {
  2957. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2958. if (this._gl.getError() !== 0) {
  2959. this._videoTextureSupported = false;
  2960. } else {
  2961. this._videoTextureSupported = true;
  2962. }
  2963. }
  2964. // Copy video through the current working canvas if video texture is not supported
  2965. if (!this._videoTextureSupported) {
  2966. if (!texture._workingCanvas) {
  2967. texture._workingCanvas = document.createElement("canvas");
  2968. let context = texture._workingCanvas.getContext("2d");
  2969. if (!context) {
  2970. throw new Error("Unable to get 2d context");
  2971. }
  2972. texture._workingContext = context;
  2973. texture._workingCanvas.width = texture.width;
  2974. texture._workingCanvas.height = texture.height;
  2975. }
  2976. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2977. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2978. } else {
  2979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2980. }
  2981. if (texture.generateMipMaps) {
  2982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2983. }
  2984. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2985. // this.resetTextureCache();
  2986. texture.isReady = true;
  2987. } catch (ex) {
  2988. // Something unexpected
  2989. // Let's disable the texture
  2990. texture._isDisabled = true;
  2991. }
  2992. }
  2993. /**
  2994. * Updates a depth texture Comparison Mode and Function.
  2995. * If the comparison Function is equal to 0, the mode will be set to none.
  2996. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  2997. * @param texture The texture to set the comparison function for
  2998. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  2999. */
  3000. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3001. if (this.webGLVersion === 1) {
  3002. Tools.Error("WebGL 1 does not support texture comparison.");
  3003. return;
  3004. }
  3005. var gl = this._gl;
  3006. if (texture.isCube) {
  3007. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3008. if (comparisonFunction === 0) {
  3009. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3011. }
  3012. else {
  3013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3015. }
  3016. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3017. } else {
  3018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3019. if (comparisonFunction === 0) {
  3020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3022. }
  3023. else {
  3024. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3025. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3026. }
  3027. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3028. }
  3029. texture._comparisonFunction = comparisonFunction;
  3030. }
  3031. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3032. var width = (<{ width: number, height: number }>size).width || <number>size;
  3033. var height = (<{ width: number, height: number }>size).height || <number>size;
  3034. internalTexture.baseWidth = width;
  3035. internalTexture.baseHeight = height;
  3036. internalTexture.width = width;
  3037. internalTexture.height = height;
  3038. internalTexture.isReady = true;
  3039. internalTexture.samples = 1;
  3040. internalTexture.generateMipMaps = false;
  3041. internalTexture._generateDepthBuffer = true;
  3042. internalTexture._generateStencilBuffer = generateStencil;
  3043. internalTexture.samplingMode = bilinearFiltering ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE;
  3044. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3045. internalTexture._comparisonFunction = comparisonFunction;
  3046. var gl = this._gl;
  3047. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3048. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  3049. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3050. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3051. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3052. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3053. if (comparisonFunction === 0) {
  3054. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3055. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3056. }
  3057. else {
  3058. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3059. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3060. }
  3061. }
  3062. /**
  3063. * Creates a depth stencil texture.
  3064. * This is only available in WebGL 2 or with the depth texture extension available.
  3065. * @param size The size of face edge in the texture.
  3066. * @param options The options defining the texture.
  3067. * @returns The texture
  3068. */
  3069. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3070. if (options.isCube) {
  3071. let width = (<{ width: number, height: number }>size).width || <number>size;
  3072. return this._createDepthStencilCubeTexture(width, options);
  3073. }
  3074. else {
  3075. return this._createDepthStencilTexture(size, options);
  3076. }
  3077. }
  3078. /**
  3079. * Creates a depth stencil texture.
  3080. * This is only available in WebGL 2 or with the depth texture extension available.
  3081. * @param size The size of face edge in the texture.
  3082. * @param options The options defining the texture.
  3083. * @returns The texture
  3084. */
  3085. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3086. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  3087. if (!this._caps.depthTextureExtension) {
  3088. Tools.Error("Depth texture is not supported by your browser or hardware.");
  3089. return internalTexture;
  3090. }
  3091. var internalOptions = {
  3092. bilinearFiltering: false,
  3093. comparisonFunction: 0,
  3094. generateStencil: false,
  3095. ...options
  3096. }
  3097. var gl = this._gl;
  3098. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  3099. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  3100. if (this.webGLVersion > 1) {
  3101. if (internalOptions.generateStencil) {
  3102. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3103. }
  3104. else {
  3105. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3106. }
  3107. }
  3108. else {
  3109. if (internalOptions.generateStencil) {
  3110. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3111. }
  3112. else {
  3113. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3114. }
  3115. }
  3116. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3117. return internalTexture;
  3118. }
  3119. /**
  3120. * Creates a depth stencil cube texture.
  3121. * This is only available in WebGL 2.
  3122. * @param size The size of face edge in the cube texture.
  3123. * @param options The options defining the cube texture.
  3124. * @returns The cube texture
  3125. */
  3126. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  3127. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  3128. internalTexture.isCube = true;
  3129. if (this.webGLVersion === 1) {
  3130. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  3131. return internalTexture;
  3132. }
  3133. var internalOptions = {
  3134. bilinearFiltering: false,
  3135. comparisonFunction: 0,
  3136. generateStencil: false,
  3137. ...options
  3138. }
  3139. var gl = this._gl;
  3140. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  3141. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  3142. // Create the depth/stencil buffer
  3143. for (var face = 0; face < 6; face++) {
  3144. if (internalOptions.generateStencil) {
  3145. 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);
  3146. }
  3147. else {
  3148. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3149. }
  3150. }
  3151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3152. return internalTexture;
  3153. }
  3154. /**
  3155. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  3156. * @param renderTarget The render target to set the frame buffer for
  3157. */
  3158. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  3159. // Create the framebuffer
  3160. var internalTexture = renderTarget.getInternalTexture();
  3161. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  3162. return;
  3163. }
  3164. var gl = this._gl;
  3165. var depthStencilTexture = renderTarget.depthStencilTexture;
  3166. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  3167. if (depthStencilTexture.isCube) {
  3168. if (depthStencilTexture._generateStencilBuffer) {
  3169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  3170. }
  3171. else {
  3172. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  3173. }
  3174. }
  3175. else {
  3176. if (depthStencilTexture._generateStencilBuffer) {
  3177. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  3178. }
  3179. else {
  3180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  3181. }
  3182. }
  3183. this.bindUnboundFramebuffer(null);
  3184. }
  3185. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  3186. let fullOptions = new RenderTargetCreationOptions();
  3187. if (options !== undefined && typeof options === "object") {
  3188. fullOptions.generateMipMaps = options.generateMipMaps;
  3189. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3190. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  3191. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  3192. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  3193. } else {
  3194. fullOptions.generateMipMaps = <boolean>options;
  3195. fullOptions.generateDepthBuffer = true;
  3196. fullOptions.generateStencilBuffer = false;
  3197. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3198. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  3199. }
  3200. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3201. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3202. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3203. }
  3204. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3205. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3206. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3207. }
  3208. var gl = this._gl;
  3209. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  3210. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3211. var width = (<{ width: number, height: number }>size).width || <number>size;
  3212. var height = (<{ width: number, height: number }>size).height || <number>size;
  3213. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  3214. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3215. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3216. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  3217. }
  3218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3221. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3222. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  3223. // Create the framebuffer
  3224. var framebuffer = gl.createFramebuffer();
  3225. this.bindUnboundFramebuffer(framebuffer);
  3226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3227. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  3228. if (fullOptions.generateMipMaps) {
  3229. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3230. }
  3231. // Unbind
  3232. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3234. this.bindUnboundFramebuffer(null);
  3235. texture._framebuffer = framebuffer;
  3236. texture.baseWidth = width;
  3237. texture.baseHeight = height;
  3238. texture.width = width;
  3239. texture.height = height;
  3240. texture.isReady = true;
  3241. texture.samples = 1;
  3242. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  3243. texture.samplingMode = fullOptions.samplingMode;
  3244. texture.type = fullOptions.type;
  3245. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  3246. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  3247. // this.resetTextureCache();
  3248. this._internalTexturesCache.push(texture);
  3249. return texture;
  3250. }
  3251. public createMultipleRenderTarget(size: any, options: any): InternalTexture[] {
  3252. var generateMipMaps = false;
  3253. var generateDepthBuffer = true;
  3254. var generateStencilBuffer = false;
  3255. var generateDepthTexture = false;
  3256. var textureCount = 1;
  3257. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  3258. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  3259. var types = [], samplingModes = [];
  3260. if (options !== undefined) {
  3261. generateMipMaps = options.generateMipMaps;
  3262. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3263. generateStencilBuffer = options.generateStencilBuffer;
  3264. generateDepthTexture = options.generateDepthTexture;
  3265. textureCount = options.textureCount || 1;
  3266. if (options.types) {
  3267. types = options.types;
  3268. }
  3269. if (options.samplingModes) {
  3270. samplingModes = options.samplingModes;
  3271. }
  3272. }
  3273. var gl = this._gl;
  3274. // Create the framebuffer
  3275. var framebuffer = gl.createFramebuffer();
  3276. this.bindUnboundFramebuffer(framebuffer);
  3277. var width = size.width || size;
  3278. var height = size.height || size;
  3279. var textures = [];
  3280. var attachments = []
  3281. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  3282. for (var i = 0; i < textureCount; i++) {
  3283. var samplingMode = samplingModes[i] || defaultSamplingMode;
  3284. var type = types[i] || defaultType;
  3285. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3286. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3287. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3288. }
  3289. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3290. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3291. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3292. }
  3293. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3294. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3295. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3296. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  3297. }
  3298. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3299. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3300. textures.push(texture);
  3301. attachments.push(attachment);
  3302. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  3303. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  3304. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3305. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3306. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3308. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3309. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3310. if (generateMipMaps) {
  3311. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3312. }
  3313. // Unbind
  3314. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3315. texture._framebuffer = framebuffer;
  3316. texture._depthStencilBuffer = depthStencilBuffer;
  3317. texture.baseWidth = width;
  3318. texture.baseHeight = height;
  3319. texture.width = width;
  3320. texture.height = height;
  3321. texture.isReady = true;
  3322. texture.samples = 1;
  3323. texture.generateMipMaps = generateMipMaps;
  3324. texture.samplingMode = samplingMode;
  3325. texture.type = type;
  3326. texture._generateDepthBuffer = generateDepthBuffer;
  3327. texture._generateStencilBuffer = generateStencilBuffer;
  3328. texture._attachments = attachments;
  3329. this._internalTexturesCache.push(texture);
  3330. }
  3331. if (generateDepthTexture && this._caps.depthTextureExtension) {
  3332. // Depth texture
  3333. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  3334. gl.activeTexture(gl.TEXTURE0);
  3335. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  3336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3340. gl.texImage2D(
  3341. gl.TEXTURE_2D,
  3342. 0,
  3343. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  3344. width,
  3345. height,
  3346. 0,
  3347. gl.DEPTH_COMPONENT,
  3348. gl.UNSIGNED_SHORT,
  3349. null
  3350. );
  3351. gl.framebufferTexture2D(
  3352. gl.FRAMEBUFFER,
  3353. gl.DEPTH_ATTACHMENT,
  3354. gl.TEXTURE_2D,
  3355. depthTexture._webGLTexture,
  3356. 0
  3357. );
  3358. depthTexture._framebuffer = framebuffer;
  3359. depthTexture.baseWidth = width;
  3360. depthTexture.baseHeight = height;
  3361. depthTexture.width = width;
  3362. depthTexture.height = height;
  3363. depthTexture.isReady = true;
  3364. depthTexture.samples = 1;
  3365. depthTexture.generateMipMaps = generateMipMaps;
  3366. depthTexture.samplingMode = gl.NEAREST;
  3367. depthTexture._generateDepthBuffer = generateDepthBuffer;
  3368. depthTexture._generateStencilBuffer = generateStencilBuffer;
  3369. textures.push(depthTexture)
  3370. this._internalTexturesCache.push(depthTexture);
  3371. }
  3372. gl.drawBuffers(attachments);
  3373. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3374. this.bindUnboundFramebuffer(null);
  3375. this.resetTextureCache();
  3376. return textures;
  3377. }
  3378. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  3379. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  3380. var gl = this._gl;
  3381. // Create the depth/stencil buffer
  3382. if (generateStencilBuffer) {
  3383. depthStencilBuffer = gl.createRenderbuffer();
  3384. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3385. if (samples > 1) {
  3386. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  3387. } else {
  3388. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  3389. }
  3390. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3391. }
  3392. else if (generateDepthBuffer) {
  3393. depthStencilBuffer = gl.createRenderbuffer();
  3394. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3395. if (samples > 1) {
  3396. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  3397. } else {
  3398. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3399. }
  3400. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  3401. }
  3402. return depthStencilBuffer;
  3403. }
  3404. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  3405. if (this.webGLVersion < 2 || !texture) {
  3406. return 1;
  3407. }
  3408. if (texture.samples === samples) {
  3409. return samples;
  3410. }
  3411. var gl = this._gl;
  3412. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3413. // Dispose previous render buffers
  3414. if (texture._depthStencilBuffer) {
  3415. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3416. texture._depthStencilBuffer = null;
  3417. }
  3418. if (texture._MSAAFramebuffer) {
  3419. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3420. texture._MSAAFramebuffer = null;
  3421. }
  3422. if (texture._MSAARenderBuffer) {
  3423. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3424. texture._MSAARenderBuffer = null;
  3425. }
  3426. if (samples > 1) {
  3427. let framebuffer = gl.createFramebuffer();
  3428. if (!framebuffer) {
  3429. throw new Error("Unable to create multi sampled framebuffer");
  3430. }
  3431. texture._MSAAFramebuffer = framebuffer;
  3432. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  3433. var colorRenderbuffer = gl.createRenderbuffer();
  3434. if (!colorRenderbuffer) {
  3435. throw new Error("Unable to create multi sampled framebuffer");
  3436. }
  3437. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3438. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3439. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  3440. texture._MSAARenderBuffer = colorRenderbuffer;
  3441. } else {
  3442. this.bindUnboundFramebuffer(texture._framebuffer);
  3443. }
  3444. texture.samples = samples;
  3445. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  3446. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3447. this.bindUnboundFramebuffer(null);
  3448. return samples;
  3449. }
  3450. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  3451. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  3452. return 1;
  3453. }
  3454. if (textures[0].samples === samples) {
  3455. return samples;
  3456. }
  3457. var gl = this._gl;
  3458. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  3459. // Dispose previous render buffers
  3460. if (textures[0]._depthStencilBuffer) {
  3461. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  3462. textures[0]._depthStencilBuffer = null;
  3463. }
  3464. if (textures[0]._MSAAFramebuffer) {
  3465. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  3466. textures[0]._MSAAFramebuffer = null;
  3467. }
  3468. for (var i = 0; i < textures.length; i++) {
  3469. if (textures[i]._MSAARenderBuffer) {
  3470. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  3471. textures[i]._MSAARenderBuffer = null;
  3472. }
  3473. }
  3474. if (samples > 1) {
  3475. let framebuffer = gl.createFramebuffer();
  3476. if (!framebuffer) {
  3477. throw new Error("Unable to create multi sampled framebuffer");
  3478. }
  3479. this.bindUnboundFramebuffer(framebuffer);
  3480. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  3481. var attachments = [];
  3482. for (var i = 0; i < textures.length; i++) {
  3483. var texture = textures[i];
  3484. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  3485. var colorRenderbuffer = gl.createRenderbuffer();
  3486. if (!colorRenderbuffer) {
  3487. throw new Error("Unable to create multi sampled framebuffer");
  3488. }
  3489. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  3490. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  3491. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  3492. texture._MSAAFramebuffer = framebuffer;
  3493. texture._MSAARenderBuffer = colorRenderbuffer;
  3494. texture.samples = samples;
  3495. texture._depthStencilBuffer = depthStencilBuffer;
  3496. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3497. attachments.push(attachment);
  3498. }
  3499. gl.drawBuffers(attachments);
  3500. } else {
  3501. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  3502. }
  3503. this.bindUnboundFramebuffer(null);
  3504. return samples;
  3505. }
  3506. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  3507. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  3508. }
  3509. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  3510. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  3511. }
  3512. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  3513. let fullOptions = {
  3514. generateMipMaps: true,
  3515. generateDepthBuffer: true,
  3516. generateStencilBuffer: false,
  3517. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3518. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  3519. ...options
  3520. };
  3521. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  3522. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  3523. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  3524. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3525. }
  3526. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  3527. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  3528. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  3529. }
  3530. var gl = this._gl
  3531. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  3532. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3533. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  3534. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  3535. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3536. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  3537. }
  3538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3541. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3542. for (var face = 0; face < 6; face++) {
  3543. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  3544. }
  3545. // Create the framebuffer
  3546. var framebuffer = gl.createFramebuffer();
  3547. this.bindUnboundFramebuffer(framebuffer);
  3548. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  3549. // MipMaps
  3550. if (fullOptions.generateMipMaps) {
  3551. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3552. }
  3553. // Unbind
  3554. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3555. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3556. this.bindUnboundFramebuffer(null);
  3557. texture._framebuffer = framebuffer;
  3558. texture.width = size;
  3559. texture.height = size;
  3560. texture.isReady = true;
  3561. texture.isCube = true;
  3562. texture.samples = 1;
  3563. texture.generateMipMaps = fullOptions.generateMipMaps;
  3564. texture.samplingMode = fullOptions.samplingMode;
  3565. texture.type = fullOptions.type;
  3566. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  3567. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  3568. this._internalTexturesCache.push(texture);
  3569. return texture;
  3570. }
  3571. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  3572. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  3573. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null): InternalTexture {
  3574. var callback = (loadData: any) => {
  3575. if (!loadData) {
  3576. if (onLoad) {
  3577. onLoad(null);
  3578. }
  3579. return;
  3580. }
  3581. let texture = loadData.texture as InternalTexture;
  3582. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  3583. texture._lodGenerationScale = scale;
  3584. texture._lodGenerationOffset = offset;
  3585. if (this._caps.textureLOD) {
  3586. // Do not add extra process if texture lod is supported.
  3587. if (onLoad) {
  3588. onLoad(texture);
  3589. }
  3590. return;
  3591. }
  3592. const mipSlices = 3;
  3593. var gl = this._gl;
  3594. const width = loadData.width;
  3595. if (!width) {
  3596. return;
  3597. }
  3598. const textures: BaseTexture[] = [];
  3599. for (let i = 0; i < mipSlices; i++) {
  3600. //compute LOD from even spacing in smoothness (matching shader calculation)
  3601. let smoothness = i / (mipSlices - 1);
  3602. let roughness = 1 - smoothness;
  3603. let minLODIndex = offset; // roughness = 0
  3604. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  3605. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  3606. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  3607. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3608. glTextureFromLod.isCube = true;
  3609. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  3610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3614. if (loadData.isDDS) {
  3615. var info: DDSInfo = loadData.info;
  3616. var data: any = loadData.data;
  3617. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3618. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  3619. }
  3620. else {
  3621. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  3622. }
  3623. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3624. // Wrap in a base texture for easy binding.
  3625. const lodTexture = new BaseTexture(scene);
  3626. lodTexture.isCube = true;
  3627. lodTexture._texture = glTextureFromLod;
  3628. glTextureFromLod.isReady = true;
  3629. textures.push(lodTexture);
  3630. }
  3631. texture._lodTextureHigh = textures[2];
  3632. texture._lodTextureMid = textures[1];
  3633. texture._lodTextureLow = textures[0];
  3634. if (onLoad) {
  3635. onLoad(texture);
  3636. }
  3637. };
  3638. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  3639. }
  3640. 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): InternalTexture {
  3641. var gl = this._gl;
  3642. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  3643. texture.isCube = true;
  3644. texture.url = rootUrl;
  3645. texture.generateMipMaps = !noMipmap;
  3646. if (!this._doNotHandleContextLost) {
  3647. texture._extension = forcedExtension;
  3648. texture._files = files;
  3649. }
  3650. var isKTX = false;
  3651. var isDDS = false;
  3652. var lastDot = rootUrl.lastIndexOf('.');
  3653. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  3654. if (this._textureFormatInUse) {
  3655. extension = this._textureFormatInUse;
  3656. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  3657. isKTX = true;
  3658. } else {
  3659. isDDS = (extension === ".dds");
  3660. }
  3661. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  3662. if (onError && request) {
  3663. onError(request.status + " " + request.statusText, exception);
  3664. }
  3665. }
  3666. if (isKTX) {
  3667. this._loadFile(rootUrl, data => {
  3668. var ktx = new KhronosTextureContainer(data, 6);
  3669. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  3670. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3671. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3672. ktx.uploadLevels(this._gl, !noMipmap);
  3673. this.setCubeMapTextureParams(gl, loadMipmap);
  3674. texture.width = ktx.pixelWidth;
  3675. texture.height = ktx.pixelHeight;
  3676. texture.isReady = true;
  3677. }, undefined, undefined, true, onerror);
  3678. } else if (isDDS) {
  3679. if (files && files.length === 6) {
  3680. this._cascadeLoadFiles(
  3681. scene,
  3682. imgs => {
  3683. var info: DDSInfo | undefined;
  3684. var loadMipmap: boolean = false;
  3685. var width: number = 0;
  3686. for (let index = 0; index < imgs.length; index++) {
  3687. let data = imgs[index];
  3688. info = DDSTools.GetDDSInfo(data);
  3689. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3690. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3691. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3692. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  3693. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3695. }
  3696. texture.width = info.width;
  3697. texture.height = info.height;
  3698. texture.type = info.textureType;
  3699. width = info.width;
  3700. }
  3701. this.setCubeMapTextureParams(gl, loadMipmap);
  3702. texture.isReady = true;
  3703. if (onLoad) {
  3704. onLoad({ isDDS: true, width: width, info, imgs, texture });
  3705. }
  3706. },
  3707. files,
  3708. onError);
  3709. } else {
  3710. this._loadFile(rootUrl,
  3711. data => {
  3712. var info = DDSTools.GetDDSInfo(data);
  3713. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3715. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  3716. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  3717. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  3718. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3719. }
  3720. this.setCubeMapTextureParams(gl, loadMipmap);
  3721. texture.width = info.width;
  3722. texture.height = info.height;
  3723. texture.isReady = true;
  3724. texture.type = info.textureType;
  3725. if (onLoad) {
  3726. onLoad({ isDDS: true, width: info.width, info, data, texture });
  3727. }
  3728. },
  3729. undefined,
  3730. undefined,
  3731. true,
  3732. onerror);
  3733. }
  3734. } else {
  3735. if (!files) {
  3736. throw new Error("Cannot load cubemap because files were not defined");
  3737. }
  3738. cascadeLoadImgs(rootUrl, scene, imgs => {
  3739. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  3740. var height = width;
  3741. this._prepareWorkingCanvas();
  3742. if (!this._workingCanvas || !this._workingContext) {
  3743. return;
  3744. }
  3745. this._workingCanvas.width = width;
  3746. this._workingCanvas.height = height;
  3747. var faces = [
  3748. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3749. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3750. ];
  3751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3752. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3753. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3754. for (var index = 0; index < faces.length; index++) {
  3755. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3756. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3757. }
  3758. if (!noMipmap) {
  3759. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3760. }
  3761. this.setCubeMapTextureParams(gl, !noMipmap);
  3762. texture.width = width;
  3763. texture.height = height;
  3764. texture.isReady = true;
  3765. if (format) {
  3766. texture.format = format;
  3767. }
  3768. texture.onLoadedObservable.notifyObservers(texture);
  3769. texture.onLoadedObservable.clear();
  3770. if (onLoad) {
  3771. onLoad();
  3772. }
  3773. }, files, onError);
  3774. }
  3775. this._internalTexturesCache.push(texture);
  3776. return texture;
  3777. }
  3778. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  3779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3783. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3784. // this.resetTextureCache();
  3785. }
  3786. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  3787. texture._bufferViewArray = data;
  3788. texture.format = format;
  3789. texture.type = type;
  3790. texture.invertY = invertY;
  3791. texture._compression = compression;
  3792. var gl = this._gl;
  3793. var textureType = this._getWebGLTextureType(type);
  3794. var internalFormat = this._getInternalFormat(format);
  3795. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3796. var needConversion = false;
  3797. if (internalFormat === gl.RGB) {
  3798. internalFormat = gl.RGBA;
  3799. needConversion = true;
  3800. }
  3801. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3802. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3803. if (texture.width % 4 !== 0) {
  3804. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3805. }
  3806. // Data are known to be in +X +Y +Z -X -Y -Z
  3807. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3808. let faceData = data[faceIndex];
  3809. if (compression) {
  3810. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, faceData);
  3811. } else {
  3812. if (needConversion) {
  3813. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3814. }
  3815. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3816. }
  3817. }
  3818. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3819. if (isPot && texture.generateMipMaps && level === 0) {
  3820. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3821. }
  3822. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3823. // this.resetTextureCache();
  3824. texture.isReady = true;
  3825. }
  3826. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3827. var gl = this._gl;
  3828. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3829. texture.isCube = true;
  3830. texture.generateMipMaps = generateMipMaps;
  3831. texture.format = format;
  3832. texture.type = type;
  3833. if (!this._doNotHandleContextLost) {
  3834. texture._bufferViewArray = data;
  3835. }
  3836. var textureType = this._getWebGLTextureType(type);
  3837. var internalFormat = this._getInternalFormat(format);
  3838. if (internalFormat === gl.RGB) {
  3839. internalFormat = gl.RGBA;
  3840. }
  3841. var width = size;
  3842. var height = width;
  3843. texture.width = width;
  3844. texture.height = height;
  3845. // Double check on POT to generate Mips.
  3846. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3847. if (!isPot) {
  3848. generateMipMaps = false;
  3849. }
  3850. // Upload data if needed. The texture won't be ready until then.
  3851. if (data) {
  3852. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3853. }
  3854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3855. // Filters
  3856. if (data && generateMipMaps) {
  3857. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3858. }
  3859. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3860. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3862. }
  3863. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3866. }
  3867. else {
  3868. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3869. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3871. }
  3872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3874. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3875. return texture;
  3876. }
  3877. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3878. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  3879. mipmmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  3880. onLoad: Nullable<() => void> = null,
  3881. onError: Nullable<(message?: string, exception?: any) => void> = null,
  3882. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3883. invertY = false): InternalTexture {
  3884. var gl = this._gl;
  3885. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3886. scene._addPendingData(texture);
  3887. texture.url = url;
  3888. this._internalTexturesCache.push(texture);
  3889. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  3890. scene._removePendingData(texture);
  3891. if (onError && request) {
  3892. onError(request.status + " " + request.statusText, exception);
  3893. }
  3894. };
  3895. var internalCallback = (data: any) => {
  3896. var width = texture.width;
  3897. var faceDataArrays = callback(data);
  3898. if (!faceDataArrays) {
  3899. return;
  3900. }
  3901. if (mipmmapGenerator) {
  3902. var textureType = this._getWebGLTextureType(type);
  3903. var internalFormat = this._getInternalFormat(format);
  3904. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3905. var needConversion = false;
  3906. if (internalFormat === gl.RGB) {
  3907. internalFormat = gl.RGBA;
  3908. needConversion = true;
  3909. }
  3910. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  3911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3912. var mipData = mipmmapGenerator(faceDataArrays);
  3913. for (var level = 0; level < mipData.length; level++) {
  3914. var mipSize = width >> level;
  3915. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3916. let mipFaceData = mipData[level][faceIndex];
  3917. if (needConversion) {
  3918. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3919. }
  3920. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3921. }
  3922. }
  3923. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3924. }
  3925. else {
  3926. texture.generateMipMaps = !noMipmap;
  3927. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3928. }
  3929. texture.isReady = true;
  3930. // this.resetTextureCache();
  3931. scene._removePendingData(texture);
  3932. if (onLoad) {
  3933. onLoad();
  3934. }
  3935. };
  3936. this._loadFile(url, data => {
  3937. internalCallback(data);
  3938. }, undefined, scene.database, true, onerror);
  3939. return texture;
  3940. };
  3941. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  3942. var internalFormat = this._getInternalFormat(format);
  3943. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3944. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3945. if (!this._doNotHandleContextLost) {
  3946. texture._bufferView = data;
  3947. texture.format = format;
  3948. texture.invertY = invertY;
  3949. texture._compression = compression;
  3950. }
  3951. if (texture.width % 4 !== 0) {
  3952. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3953. }
  3954. if (compression && data) {
  3955. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  3956. } else {
  3957. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  3958. }
  3959. if (texture.generateMipMaps) {
  3960. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3961. }
  3962. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3963. // this.resetTextureCache();
  3964. texture.isReady = true;
  3965. }
  3966. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  3967. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  3968. texture.baseWidth = width;
  3969. texture.baseHeight = height;
  3970. texture.baseDepth = depth;
  3971. texture.width = width;
  3972. texture.height = height;
  3973. texture.depth = depth;
  3974. texture.format = format;
  3975. texture.generateMipMaps = generateMipMaps;
  3976. texture.samplingMode = samplingMode;
  3977. texture.is3D = true;
  3978. if (!this._doNotHandleContextLost) {
  3979. texture._bufferView = data;
  3980. }
  3981. this.updateRawTexture3D(texture, data, format, invertY, compression);
  3982. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  3983. // Filters
  3984. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3985. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3986. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3987. if (generateMipMaps) {
  3988. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  3989. }
  3990. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3991. this._internalTexturesCache.push(texture);
  3992. return texture;
  3993. }
  3994. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3995. var gl = this._gl;
  3996. if (!gl) {
  3997. return;
  3998. }
  3999. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  4000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4002. if (!noMipmap && !isCompressed) {
  4003. gl.generateMipmap(gl.TEXTURE_2D);
  4004. }
  4005. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4006. // this.resetTextureCache();
  4007. if (scene) {
  4008. scene._removePendingData(texture);
  4009. }
  4010. texture.onLoadedObservable.notifyObservers(texture);
  4011. texture.onLoadedObservable.clear();
  4012. }
  4013. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  4014. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  4015. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  4016. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  4017. var gl = this._gl;
  4018. if (!gl) {
  4019. return;
  4020. }
  4021. if (!texture._webGLTexture) {
  4022. // this.resetTextureCache();
  4023. if (scene) {
  4024. scene._removePendingData(texture);
  4025. }
  4026. return;
  4027. }
  4028. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4029. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4030. texture.baseWidth = width;
  4031. texture.baseHeight = height;
  4032. texture.width = potWidth;
  4033. texture.height = potHeight;
  4034. texture.isReady = true;
  4035. if (processFunction(potWidth, potHeight, () => {
  4036. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  4037. })) {
  4038. // Returning as texture needs extra async steps
  4039. return;
  4040. }
  4041. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  4042. }
  4043. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  4044. // Create new RGBA data container.
  4045. var rgbaData: any;
  4046. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  4047. rgbaData = new Float32Array(width * height * 4);
  4048. }
  4049. else {
  4050. rgbaData = new Uint32Array(width * height * 4);
  4051. }
  4052. // Convert each pixel.
  4053. for (let x = 0; x < width; x++) {
  4054. for (let y = 0; y < height; y++) {
  4055. let index = (y * width + x) * 3;
  4056. let newIndex = (y * width + x) * 4;
  4057. // Map Old Value to new value.
  4058. rgbaData[newIndex + 0] = rgbData[index + 0];
  4059. rgbaData[newIndex + 1] = rgbData[index + 1];
  4060. rgbaData[newIndex + 2] = rgbData[index + 2];
  4061. // Add fully opaque alpha channel.
  4062. rgbaData[newIndex + 3] = 1;
  4063. }
  4064. }
  4065. return rgbaData;
  4066. }
  4067. public _releaseFramebufferObjects(texture: InternalTexture): void {
  4068. var gl = this._gl;
  4069. if (texture._framebuffer) {
  4070. gl.deleteFramebuffer(texture._framebuffer);
  4071. texture._framebuffer = null;
  4072. }
  4073. if (texture._depthStencilBuffer) {
  4074. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4075. texture._depthStencilBuffer = null;
  4076. }
  4077. if (texture._MSAAFramebuffer) {
  4078. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4079. texture._MSAAFramebuffer = null;
  4080. }
  4081. if (texture._MSAARenderBuffer) {
  4082. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4083. texture._MSAARenderBuffer = null;
  4084. }
  4085. }
  4086. public _releaseTexture(texture: InternalTexture): void {
  4087. var gl = this._gl;
  4088. this._releaseFramebufferObjects(texture);
  4089. gl.deleteTexture(texture._webGLTexture);
  4090. // Unbind channels
  4091. this.unbindAllTextures();
  4092. var index = this._internalTexturesCache.indexOf(texture);
  4093. if (index !== -1) {
  4094. this._internalTexturesCache.splice(index, 1);
  4095. }
  4096. // Integrated fixed lod samplers.
  4097. if (texture._lodTextureHigh) {
  4098. texture._lodTextureHigh.dispose();
  4099. }
  4100. if (texture._lodTextureMid) {
  4101. texture._lodTextureMid.dispose();
  4102. }
  4103. if (texture._lodTextureLow) {
  4104. texture._lodTextureLow.dispose();
  4105. }
  4106. }
  4107. private setProgram(program: WebGLProgram): void {
  4108. if (this._currentProgram !== program) {
  4109. this._gl.useProgram(program);
  4110. this._currentProgram = program;
  4111. }
  4112. }
  4113. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  4114. public bindSamplers(effect: Effect): void {
  4115. this.setProgram(effect.getProgram());
  4116. var samplers = effect.getSamplers();
  4117. for (var index = 0; index < samplers.length; index++) {
  4118. var uniform = effect.getUniform(samplers[index]);
  4119. if (uniform) {
  4120. this._boundUniforms[index] = uniform;
  4121. }
  4122. }
  4123. this._currentEffect = null;
  4124. }
  4125. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  4126. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  4127. return;
  4128. }
  4129. // Remove
  4130. this._linkTrackers(internalTexture.previous, internalTexture.next);
  4131. // Bind last to it
  4132. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  4133. // Bind to dummy
  4134. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  4135. }
  4136. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  4137. if (!internalTexture) {
  4138. return -1;
  4139. }
  4140. internalTexture._initialSlot = channel;
  4141. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  4142. if (channel !== internalTexture._designatedSlot) {
  4143. this._textureCollisions.addCount(1, false);
  4144. }
  4145. } else {
  4146. if (channel !== internalTexture._designatedSlot) {
  4147. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  4148. return internalTexture._designatedSlot;
  4149. } else {
  4150. // No slot for this texture, let's pick a new one (if we find a free slot)
  4151. if (this._nextFreeTextureSlots.length) {
  4152. return this._nextFreeTextureSlots[0];
  4153. }
  4154. // We need to recycle the oldest bound texture, sorry.
  4155. this._textureCollisions.addCount(1, false);
  4156. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  4157. }
  4158. }
  4159. }
  4160. return channel;
  4161. }
  4162. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  4163. previous!.next = next;
  4164. next!.previous = previous;
  4165. }
  4166. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  4167. let currentSlot = internalTexture._designatedSlot;
  4168. if (currentSlot === -1) {
  4169. return -1;
  4170. }
  4171. internalTexture._designatedSlot = -1;
  4172. if (this.disableTextureBindingOptimization) {
  4173. return -1;
  4174. }
  4175. // Remove from bound list
  4176. this._linkTrackers(internalTexture.previous, internalTexture.next);
  4177. // Free the slot
  4178. this._boundTexturesCache[currentSlot] = null;
  4179. this._nextFreeTextureSlots.push(currentSlot);
  4180. return currentSlot;
  4181. }
  4182. private _activateCurrentTexture() {
  4183. if (this._currentTextureChannel !== this._activeChannel) {
  4184. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  4185. this._currentTextureChannel = this._activeChannel;
  4186. }
  4187. }
  4188. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false): void {
  4189. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  4190. this._activeChannel = texture._designatedSlot;
  4191. }
  4192. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  4193. let isTextureForRendering = texture && texture._initialSlot > -1;
  4194. if (currentTextureBound !== texture) {
  4195. if (currentTextureBound) {
  4196. this._removeDesignatedSlot(currentTextureBound);
  4197. }
  4198. this._activateCurrentTexture();
  4199. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  4200. this._boundTexturesCache[this._activeChannel] = texture;
  4201. if (texture) {
  4202. if (!this.disableTextureBindingOptimization) {
  4203. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  4204. if (slotIndex > -1) {
  4205. this._nextFreeTextureSlots.splice(slotIndex, 1);
  4206. }
  4207. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  4208. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  4209. }
  4210. texture._designatedSlot = this._activeChannel;
  4211. }
  4212. } else if (forTextureDataUpdate) {
  4213. this._activateCurrentTexture();
  4214. }
  4215. if (isTextureForRendering && !forTextureDataUpdate) {
  4216. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  4217. }
  4218. }
  4219. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  4220. if (channel < 0) {
  4221. return;
  4222. }
  4223. if (texture) {
  4224. channel = this._getCorrectTextureChannel(channel, texture);
  4225. }
  4226. this._activeChannel = channel;
  4227. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  4228. }
  4229. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  4230. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  4231. }
  4232. public unbindAllTextures(): void {
  4233. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  4234. this._activeChannel = channel;
  4235. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4236. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4237. if (this.webGLVersion > 1) {
  4238. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4239. }
  4240. }
  4241. }
  4242. /**
  4243. * Sets a texture to the according uniform.
  4244. * @param channel The texture channel
  4245. * @param uniform The uniform to set
  4246. * @param texture The texture to apply
  4247. */
  4248. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  4249. if (channel < 0) {
  4250. return;
  4251. }
  4252. if (uniform) {
  4253. this._boundUniforms[channel] = uniform;
  4254. }
  4255. this._setTexture(channel, texture);
  4256. }
  4257. /**
  4258. * Sets a depth stencil texture from a render target to the according uniform.
  4259. * @param channel The texture channel
  4260. * @param uniform The uniform to set
  4261. * @param texture The render target texture containing the depth stencil texture to apply
  4262. */
  4263. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  4264. if (channel < 0) {
  4265. return;
  4266. }
  4267. if (uniform) {
  4268. this._boundUniforms[channel] = uniform;
  4269. }
  4270. if (!texture || !texture.depthStencilTexture) {
  4271. this._setTexture(channel, null);
  4272. }
  4273. else {
  4274. this._setTexture(channel, texture, false, true);
  4275. }
  4276. }
  4277. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  4278. let uniform = this._boundUniforms[sourceSlot];
  4279. if (uniform._currentState === destination) {
  4280. return;
  4281. }
  4282. this._gl.uniform1i(uniform, destination);
  4283. uniform._currentState = destination;
  4284. }
  4285. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  4286. // Not ready?
  4287. if (!texture) {
  4288. if (this._boundTexturesCache[channel] != null) {
  4289. this._activeChannel = channel;
  4290. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4291. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4292. if (this.webGLVersion > 1) {
  4293. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4294. }
  4295. }
  4296. return false;
  4297. }
  4298. // Video
  4299. if ((<VideoTexture>texture).video) {
  4300. this._activeChannel = channel;
  4301. (<VideoTexture>texture).update();
  4302. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  4303. texture.delayLoad();
  4304. return false;
  4305. }
  4306. let internalTexture: InternalTexture;
  4307. if (depthStencilTexture) {
  4308. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  4309. }
  4310. else if (texture.isReady()) {
  4311. internalTexture = <InternalTexture>texture.getInternalTexture();
  4312. }
  4313. else if (texture.isCube) {
  4314. internalTexture = this.emptyCubeTexture;
  4315. }
  4316. else if (texture.is3D) {
  4317. internalTexture = this.emptyTexture3D;
  4318. }
  4319. else {
  4320. internalTexture = this.emptyTexture;
  4321. }
  4322. if (!isPartOfTextureArray) {
  4323. channel = this._getCorrectTextureChannel(channel, internalTexture);
  4324. }
  4325. if (this._boundTexturesCache[channel] === internalTexture) {
  4326. this._moveBoundTextureOnTop(internalTexture);
  4327. if (!isPartOfTextureArray) {
  4328. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  4329. }
  4330. return false;
  4331. }
  4332. this._activeChannel = channel;
  4333. if (internalTexture && internalTexture.is3D) {
  4334. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  4335. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4336. internalTexture._cachedWrapU = texture.wrapU;
  4337. switch (texture.wrapU) {
  4338. case Texture.WRAP_ADDRESSMODE:
  4339. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4340. break;
  4341. case Texture.CLAMP_ADDRESSMODE:
  4342. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4343. break;
  4344. case Texture.MIRROR_ADDRESSMODE:
  4345. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4346. break;
  4347. }
  4348. }
  4349. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4350. internalTexture._cachedWrapV = texture.wrapV;
  4351. switch (texture.wrapV) {
  4352. case Texture.WRAP_ADDRESSMODE:
  4353. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4354. break;
  4355. case Texture.CLAMP_ADDRESSMODE:
  4356. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4357. break;
  4358. case Texture.MIRROR_ADDRESSMODE:
  4359. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4360. break;
  4361. }
  4362. }
  4363. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  4364. internalTexture._cachedWrapR = texture.wrapR;
  4365. switch (texture.wrapR) {
  4366. case Texture.WRAP_ADDRESSMODE:
  4367. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  4368. break;
  4369. case Texture.CLAMP_ADDRESSMODE:
  4370. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  4371. break;
  4372. case Texture.MIRROR_ADDRESSMODE:
  4373. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  4374. break;
  4375. }
  4376. }
  4377. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  4378. }
  4379. else if (internalTexture && internalTexture.isCube) {
  4380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  4381. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4382. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4383. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4384. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4385. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4386. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4387. }
  4388. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4389. } else {
  4390. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  4391. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  4392. internalTexture._cachedWrapU = texture.wrapU;
  4393. switch (texture.wrapU) {
  4394. case Texture.WRAP_ADDRESSMODE:
  4395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4396. break;
  4397. case Texture.CLAMP_ADDRESSMODE:
  4398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4399. break;
  4400. case Texture.MIRROR_ADDRESSMODE:
  4401. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4402. break;
  4403. }
  4404. }
  4405. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  4406. internalTexture._cachedWrapV = texture.wrapV;
  4407. switch (texture.wrapV) {
  4408. case Texture.WRAP_ADDRESSMODE:
  4409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4410. break;
  4411. case Texture.CLAMP_ADDRESSMODE:
  4412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4413. break;
  4414. case Texture.MIRROR_ADDRESSMODE:
  4415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4416. break;
  4417. }
  4418. }
  4419. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4420. }
  4421. return true;
  4422. }
  4423. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  4424. if (channel < 0 || !uniform) {
  4425. return;
  4426. }
  4427. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  4428. this._textureUnits = new Int32Array(textures.length);
  4429. }
  4430. for (let i = 0; i < textures.length; i++) {
  4431. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  4432. }
  4433. this._gl.uniform1iv(uniform, this._textureUnits);
  4434. for (var index = 0; index < textures.length; index++) {
  4435. this._setTexture(this._textureUnits[index], textures[index], true);
  4436. }
  4437. }
  4438. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  4439. var internalTexture = texture.getInternalTexture();
  4440. if (!internalTexture) {
  4441. return;
  4442. }
  4443. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4444. var value = texture.anisotropicFilteringLevel;
  4445. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  4446. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  4447. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  4448. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  4449. }
  4450. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  4451. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  4452. internalTexture._cachedAnisotropicFilteringLevel = value;
  4453. }
  4454. }
  4455. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  4456. var data = new Uint8Array(height * width * 4);
  4457. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4458. return data;
  4459. }
  4460. /**
  4461. * Add an externaly attached data from its key.
  4462. * This method call will fail and return false, if such key already exists.
  4463. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4464. * @param key the unique key that identifies the data
  4465. * @param data the data object to associate to the key for this Engine instance
  4466. * @return true if no such key were already present and the data was added successfully, false otherwise
  4467. */
  4468. public addExternalData<T>(key: string, data: T): boolean {
  4469. if (!this._externalData) {
  4470. this._externalData = new StringDictionary<Object>();
  4471. }
  4472. return this._externalData.add(key, data);
  4473. }
  4474. /**
  4475. * Get an externaly attached data from its key
  4476. * @param key the unique key that identifies the data
  4477. * @return the associated data, if present (can be null), or undefined if not present
  4478. */
  4479. public getExternalData<T>(key: string): T {
  4480. if (!this._externalData) {
  4481. this._externalData = new StringDictionary<Object>();
  4482. }
  4483. return <T>this._externalData.get(key);
  4484. }
  4485. /**
  4486. * Get an externaly attached data from its key, create it using a factory if it's not already present
  4487. * @param key the unique key that identifies the data
  4488. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4489. * @return the associated data, can be null if the factory returned null.
  4490. */
  4491. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  4492. if (!this._externalData) {
  4493. this._externalData = new StringDictionary<Object>();
  4494. }
  4495. return <T>this._externalData.getOrAddWithFactory(key, factory);
  4496. }
  4497. /**
  4498. * Remove an externaly attached data from the Engine instance
  4499. * @param key the unique key that identifies the data
  4500. * @return true if the data was successfully removed, false if it doesn't exist
  4501. */
  4502. public removeExternalData(key: string): boolean {
  4503. if (!this._externalData) {
  4504. this._externalData = new StringDictionary<Object>();
  4505. }
  4506. return this._externalData.remove(key);
  4507. }
  4508. public unbindAllAttributes() {
  4509. if (this._mustWipeVertexAttributes) {
  4510. this._mustWipeVertexAttributes = false;
  4511. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  4512. this._gl.disableVertexAttribArray(i);
  4513. this._vertexAttribArraysEnabled[i] = false;
  4514. this._currentBufferPointers[i].active = false;
  4515. }
  4516. return;
  4517. }
  4518. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  4519. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  4520. continue;
  4521. }
  4522. this._gl.disableVertexAttribArray(i);
  4523. this._vertexAttribArraysEnabled[i] = false;
  4524. this._currentBufferPointers[i].active = false;
  4525. }
  4526. }
  4527. public releaseEffects() {
  4528. for (var name in this._compiledEffects) {
  4529. this._deleteProgram(this._compiledEffects[name]._program)
  4530. }
  4531. this._compiledEffects = {};
  4532. }
  4533. // Dispose
  4534. public dispose(): void {
  4535. this.hideLoadingUI();
  4536. this.stopRenderLoop();
  4537. // Release postProcesses
  4538. while (this.postProcesses.length) {
  4539. this.postProcesses[0].dispose();
  4540. }
  4541. // Empty texture
  4542. if (this._emptyTexture) {
  4543. this._releaseTexture(this._emptyTexture);
  4544. this._emptyTexture = null;
  4545. }
  4546. if (this._emptyCubeTexture) {
  4547. this._releaseTexture(this._emptyCubeTexture);
  4548. this._emptyCubeTexture = null;
  4549. }
  4550. // Rescale PP
  4551. if (this._rescalePostProcess) {
  4552. this._rescalePostProcess.dispose();
  4553. }
  4554. // Release scenes
  4555. while (this.scenes.length) {
  4556. this.scenes[0].dispose();
  4557. }
  4558. // Release audio engine
  4559. if (Engine.audioEngine) {
  4560. Engine.audioEngine.dispose();
  4561. }
  4562. // Release effects
  4563. this.releaseEffects();
  4564. // Unbind
  4565. this.unbindAllAttributes();
  4566. if (this._dummyFramebuffer) {
  4567. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  4568. }
  4569. //WebVR
  4570. this.disableVR();
  4571. // Events
  4572. if (Tools.IsWindowObjectExist()) {
  4573. window.removeEventListener("blur", this._onBlur);
  4574. window.removeEventListener("focus", this._onFocus);
  4575. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  4576. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  4577. if (this._renderingCanvas) {
  4578. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  4579. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  4580. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  4581. if (!this._doNotHandleContextLost) {
  4582. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  4583. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  4584. }
  4585. }
  4586. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4587. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4588. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4589. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4590. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4591. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4592. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4593. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4594. if (this._onVrDisplayConnect) {
  4595. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  4596. if (this._onVrDisplayDisconnect) {
  4597. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  4598. }
  4599. if (this._onVrDisplayPresentChange) {
  4600. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  4601. }
  4602. this._onVrDisplayConnect = null;
  4603. this._onVrDisplayDisconnect = null;
  4604. }
  4605. }
  4606. // Remove from Instances
  4607. var index = Engine.Instances.indexOf(this);
  4608. if (index >= 0) {
  4609. Engine.Instances.splice(index, 1);
  4610. }
  4611. this._workingCanvas = null;
  4612. this._workingContext = null;
  4613. this._currentBufferPointers = [];
  4614. this._renderingCanvas = null;
  4615. this._currentProgram = null;
  4616. this._bindedRenderFunction = null;
  4617. this.onResizeObservable.clear();
  4618. this.onCanvasBlurObservable.clear();
  4619. this.onCanvasFocusObservable.clear();
  4620. this.onCanvasPointerOutObservable.clear();
  4621. this.onBeginFrameObservable.clear();
  4622. this.onEndFrameObservable.clear();
  4623. Effect.ResetCache();
  4624. // Abort active requests
  4625. for (let request of this._activeRequests) {
  4626. request.abort();
  4627. }
  4628. }
  4629. // Loading screen
  4630. public displayLoadingUI(): void {
  4631. if (!Tools.IsWindowObjectExist()) {
  4632. return;
  4633. }
  4634. const loadingScreen = this.loadingScreen;
  4635. if (loadingScreen) {
  4636. loadingScreen.displayLoadingUI();
  4637. }
  4638. }
  4639. public hideLoadingUI(): void {
  4640. if (!Tools.IsWindowObjectExist()) {
  4641. return;
  4642. }
  4643. const loadingScreen = this.loadingScreen;
  4644. if (loadingScreen) {
  4645. loadingScreen.hideLoadingUI();
  4646. }
  4647. }
  4648. public get loadingScreen(): ILoadingScreen {
  4649. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  4650. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  4651. return this._loadingScreen;
  4652. }
  4653. public set loadingScreen(loadingScreen: ILoadingScreen) {
  4654. this._loadingScreen = loadingScreen;
  4655. }
  4656. public set loadingUIText(text: string) {
  4657. this.loadingScreen.loadingUIText = text;
  4658. }
  4659. public set loadingUIBackgroundColor(color: string) {
  4660. this.loadingScreen.loadingUIBackgroundColor = color;
  4661. }
  4662. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4663. if (this._renderingCanvas) {
  4664. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  4665. }
  4666. }
  4667. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  4668. if (this._renderingCanvas) {
  4669. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  4670. }
  4671. }
  4672. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  4673. var shaders = this._gl.getAttachedShaders(program);
  4674. if (!shaders) {
  4675. return null;
  4676. }
  4677. return this._gl.getShaderSource(shaders[0]);
  4678. }
  4679. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  4680. var shaders = this._gl.getAttachedShaders(program);
  4681. if (!shaders) {
  4682. return null;
  4683. }
  4684. return this._gl.getShaderSource(shaders[1]);
  4685. }
  4686. public getError(): number {
  4687. return this._gl.getError();
  4688. }
  4689. // FPS
  4690. public getFps(): number {
  4691. return this._fps;
  4692. }
  4693. public getDeltaTime(): number {
  4694. return this._deltaTime;
  4695. }
  4696. private _measureFps(): void {
  4697. this._performanceMonitor.sampleFrame();
  4698. this._fps = this._performanceMonitor.averageFPS;
  4699. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  4700. }
  4701. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  4702. let gl = this._gl;
  4703. if (!this._dummyFramebuffer) {
  4704. let dummy = gl.createFramebuffer();
  4705. if (!dummy) {
  4706. throw new Error("Unable to create dummy framebuffer");
  4707. }
  4708. this._dummyFramebuffer = dummy;
  4709. }
  4710. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  4711. if (faceIndex > -1) {
  4712. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  4713. } else {
  4714. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4715. }
  4716. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  4717. let buffer: ArrayBufferView;
  4718. switch (readType) {
  4719. case gl.UNSIGNED_BYTE:
  4720. buffer = new Uint8Array(4 * width * height);
  4721. readType = gl.UNSIGNED_BYTE;
  4722. break;
  4723. default:
  4724. buffer = new Float32Array(4 * width * height);
  4725. readType = gl.FLOAT;
  4726. break;
  4727. }
  4728. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  4729. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  4730. return buffer;
  4731. }
  4732. private _canRenderToFloatFramebuffer(): boolean {
  4733. if (this._webGLVersion > 1) {
  4734. return this._caps.colorBufferFloat;
  4735. }
  4736. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  4737. }
  4738. private _canRenderToHalfFloatFramebuffer(): boolean {
  4739. if (this._webGLVersion > 1) {
  4740. return this._caps.colorBufferFloat;
  4741. }
  4742. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  4743. }
  4744. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  4745. private _canRenderToFramebuffer(type: number): boolean {
  4746. let gl = this._gl;
  4747. //clear existing errors
  4748. while (gl.getError() !== gl.NO_ERROR) { }
  4749. let successful = true;
  4750. let texture = gl.createTexture();
  4751. gl.bindTexture(gl.TEXTURE_2D, texture);
  4752. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4754. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4755. let fb = gl.createFramebuffer();
  4756. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  4757. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4758. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  4759. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  4760. successful = successful && (gl.getError() === gl.NO_ERROR);
  4761. //try render by clearing frame buffer's color buffer
  4762. if (successful) {
  4763. gl.clear(gl.COLOR_BUFFER_BIT);
  4764. successful = successful && (gl.getError() === gl.NO_ERROR);
  4765. }
  4766. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  4767. if (successful) {
  4768. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  4769. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4770. let readFormat = gl.RGBA;
  4771. let readType = gl.UNSIGNED_BYTE;
  4772. let buffer = new Uint8Array(4);
  4773. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  4774. successful = successful && (gl.getError() === gl.NO_ERROR);
  4775. }
  4776. //clean up
  4777. gl.deleteTexture(texture);
  4778. gl.deleteFramebuffer(fb);
  4779. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4780. //clear accumulated errors
  4781. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  4782. return successful;
  4783. }
  4784. public _getWebGLTextureType(type: number): number {
  4785. if (type === Engine.TEXTURETYPE_FLOAT) {
  4786. return this._gl.FLOAT;
  4787. }
  4788. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4789. // Add Half Float Constant.
  4790. return this._gl.HALF_FLOAT_OES;
  4791. }
  4792. return this._gl.UNSIGNED_BYTE;
  4793. };
  4794. /** @ignore */
  4795. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  4796. if (this._webGLVersion === 1) {
  4797. return this._gl.RGBA;
  4798. }
  4799. if (type === Engine.TEXTURETYPE_FLOAT) {
  4800. if (format) {
  4801. switch(format) {
  4802. case Engine.TEXTUREFORMAT_R32F:
  4803. return this._gl.R32F;
  4804. case Engine.TEXTUREFORMAT_RG32F:
  4805. return this._gl.RG32F;
  4806. case Engine.TEXTUREFORMAT_RGB32F:
  4807. return this._gl.RGB32F;
  4808. }
  4809. }
  4810. return this._gl.RGBA32F;
  4811. }
  4812. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4813. return this._gl.RGBA16F;
  4814. }
  4815. return this._gl.RGBA;
  4816. };
  4817. public _getRGBAMultiSampleBufferFormat(type: number): number {
  4818. if (type === Engine.TEXTURETYPE_FLOAT) {
  4819. return this._gl.RGBA32F;
  4820. }
  4821. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  4822. return this._gl.RGBA16F;
  4823. }
  4824. return this._gl.RGBA8;
  4825. };
  4826. public createQuery(): WebGLQuery {
  4827. return this._gl.createQuery();
  4828. }
  4829. public deleteQuery(query: WebGLQuery): Engine {
  4830. this._gl.deleteQuery(query);
  4831. return this;
  4832. }
  4833. public isQueryResultAvailable(query: WebGLQuery): boolean {
  4834. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  4835. }
  4836. public getQueryResult(query: WebGLQuery): number {
  4837. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  4838. }
  4839. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  4840. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4841. this._gl.beginQuery(glAlgorithm, query);
  4842. return this;
  4843. }
  4844. public endOcclusionQuery(algorithmType: number): Engine {
  4845. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  4846. this._gl.endQuery(glAlgorithm);
  4847. return this;
  4848. }
  4849. /* Time queries */
  4850. private _createTimeQuery(): WebGLQuery {
  4851. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4852. if (timerQuery.createQueryEXT) {
  4853. return timerQuery.createQueryEXT();
  4854. }
  4855. return this.createQuery();
  4856. }
  4857. private _deleteTimeQuery(query: WebGLQuery): void {
  4858. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4859. if (timerQuery.deleteQueryEXT) {
  4860. timerQuery.deleteQueryEXT(query);
  4861. return;
  4862. }
  4863. this.deleteQuery(query);
  4864. }
  4865. private _getTimeQueryResult(query: WebGLQuery): any {
  4866. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4867. if (timerQuery.getQueryObjectEXT) {
  4868. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  4869. }
  4870. return this.getQueryResult(query);
  4871. }
  4872. private _getTimeQueryAvailability(query: WebGLQuery): any {
  4873. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  4874. if (timerQuery.getQueryObjectEXT) {
  4875. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  4876. }
  4877. return this.isQueryResultAvailable(query);
  4878. }
  4879. private _currentNonTimestampToken: Nullable<_TimeToken>;
  4880. public startTimeQuery(): Nullable<_TimeToken> {
  4881. let timerQuery = this._caps.timerQuery;
  4882. if (!timerQuery) {
  4883. return null;
  4884. }
  4885. let token = new _TimeToken();
  4886. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4887. if (this._caps.canUseTimestampForTimerQuery) {
  4888. token._startTimeQuery = this._createTimeQuery();
  4889. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  4890. } else {
  4891. if (this._currentNonTimestampToken) {
  4892. return this._currentNonTimestampToken;
  4893. }
  4894. token._timeElapsedQuery = this._createTimeQuery();
  4895. if (timerQuery.beginQueryEXT) {
  4896. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4897. } else {
  4898. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  4899. }
  4900. this._currentNonTimestampToken = token;
  4901. }
  4902. return token;
  4903. }
  4904. public endTimeQuery(token: _TimeToken): int {
  4905. let timerQuery = this._caps.timerQuery;
  4906. if (!timerQuery || !token) {
  4907. return -1;
  4908. }
  4909. if (this._caps.canUseTimestampForTimerQuery) {
  4910. if (!token._startTimeQuery) {
  4911. return -1;
  4912. }
  4913. if (!token._endTimeQuery) {
  4914. token._endTimeQuery = this._createTimeQuery();
  4915. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  4916. }
  4917. } else if (!token._timeElapsedQueryEnded) {
  4918. if (!token._timeElapsedQuery) {
  4919. return -1;
  4920. }
  4921. if (timerQuery.endQueryEXT) {
  4922. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  4923. } else {
  4924. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  4925. }
  4926. token._timeElapsedQueryEnded = true;
  4927. }
  4928. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  4929. let available: boolean = false;
  4930. if (token._endTimeQuery) {
  4931. available = this._getTimeQueryAvailability(token._endTimeQuery);
  4932. } else if (token._timeElapsedQuery) {
  4933. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  4934. }
  4935. if (available && !disjoint) {
  4936. let result = 0;
  4937. if (this._caps.canUseTimestampForTimerQuery) {
  4938. if (!token._startTimeQuery || !token._endTimeQuery) {
  4939. return -1;
  4940. }
  4941. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  4942. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  4943. result = timeEnd - timeStart;
  4944. this._deleteTimeQuery(token._startTimeQuery);
  4945. this._deleteTimeQuery(token._endTimeQuery);
  4946. token._startTimeQuery = null;
  4947. token._endTimeQuery = null;
  4948. } else {
  4949. if (!token._timeElapsedQuery) {
  4950. return -1;
  4951. }
  4952. result = this._getTimeQueryResult(token._timeElapsedQuery);
  4953. this._deleteTimeQuery(token._timeElapsedQuery);
  4954. token._timeElapsedQuery = null;
  4955. token._timeElapsedQueryEnded = false;
  4956. this._currentNonTimestampToken = null;
  4957. }
  4958. return result;
  4959. }
  4960. return -1;
  4961. }
  4962. private getGlAlgorithmType(algorithmType: number): number {
  4963. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  4964. }
  4965. // Transform feedback
  4966. public createTransformFeedback(): WebGLTransformFeedback {
  4967. return this._gl.createTransformFeedback();
  4968. }
  4969. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  4970. this._gl.deleteTransformFeedback(value);
  4971. }
  4972. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  4973. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  4974. }
  4975. public beginTransformFeedback(usePoints: boolean = true): void {
  4976. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  4977. }
  4978. public endTransformFeedback(): void {
  4979. this._gl.endTransformFeedback();
  4980. }
  4981. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  4982. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  4983. }
  4984. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  4985. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  4986. }
  4987. 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 {
  4988. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  4989. this._activeRequests.push(request);
  4990. request.onCompleteObservable.add(request => {
  4991. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  4992. });
  4993. return request;
  4994. }
  4995. /** @ignore */
  4996. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  4997. return new Promise((resolve, reject) => {
  4998. this._loadFile(url, (data) => {
  4999. resolve(data);
  5000. }, undefined, database, useArrayBuffer, (request, exception) => {
  5001. reject(exception);
  5002. })
  5003. });
  5004. }
  5005. 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 {
  5006. var onload = (data: string | ArrayBuffer) => {
  5007. loadedFiles[index] = data;
  5008. (<any>loadedFiles)._internalCount++;
  5009. if ((<any>loadedFiles)._internalCount === 6) {
  5010. onfinish(loadedFiles);
  5011. }
  5012. };
  5013. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  5014. if (onErrorCallBack && request) {
  5015. onErrorCallBack(request.status + " " + request.statusText, exception);
  5016. }
  5017. };
  5018. this._loadFile(url, onload, undefined, undefined, true, onerror);
  5019. }
  5020. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  5021. var loadedFiles: (string | ArrayBuffer)[] = [];
  5022. (<any>loadedFiles)._internalCount = 0;
  5023. for (let index = 0; index < 6; index++) {
  5024. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  5025. }
  5026. }
  5027. // Statics
  5028. public static isSupported(): boolean {
  5029. try {
  5030. var tempcanvas = document.createElement("canvas");
  5031. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5032. return gl != null && !!window.WebGLRenderingContext;
  5033. } catch (e) {
  5034. return false;
  5035. }
  5036. }
  5037. }
  5038. }